Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Creative Commons License 

import java.util.HashMap;
import java.util.HashSet;

import java.util.function.Predicate;

public class Main {
    /**
     * Returns a HashSet of values in a HashMap that match the specified Predicate.
     * @param map the HashMap to check against
     * @param condition the Predicate to check
     * @param <K> the type of the Key in the HashMap
     * @param <V> the type of the Value in the HashMap
     * @return a HashSet of values matching the predicate, empty HashSet if no results found
     * @throws IllegalArgumentException if HashMap or Predicate is null
     */
    public static <K, V> HashSet<V> getValuesInHashMap(final HashMap<K, V> map, final Predicate<V> condition) {
        final HashSet<V> matchingValues = new HashSet<>();

        if (map == null)
            throw new IllegalArgumentException("HashMap cannot be null!");
        if (condition == null)
            throw new IllegalArgumentException("Predicate cannot be null!");

        map.forEach((key, value) -> {
            if (condition.test(value))
                matchingValues.add(value);
        });

        return matchingValues;
    }
}