Max Beaver
Max Beaver

Reputation: 93

Java 8 check a hashmap equality of its keys to a list containing keys and return the hashmap value where they are equal

I would like to iterate over a hashmap with Java 8, comparing its keys to a given list (containing objects with key ID) and return the values from the hashmap where the key of the hashmap and the key of the object in the list are equal. I can't figure this out.

I try to accomplish something like this:

someHashMap.entrySet()
    .stream()
    .filter(entry -> entry.getValue().equals(something.stream().iterator().next().getID()))
    .map(map -> map.getValue())
    .collect(Collectors.toList());

Upvotes: 3

Views: 9323

Answers (1)

castletheperson
castletheperson

Reputation: 33476

If you have these objects initialized:

Map<K,V> someHashMap;
List<K> something;

You can get a list of values from the Map by iterating over the List like this:

List<V> values = something.stream()
                        //.distinct() // include this if there may be duplicate keys
                          .filter(someHashMap::containsKey)
                          .map(someHashMap::get)
                          .collect(Collectors.toList());

Or if you want to iterate over the Map (which is slower), you could use:

List<V> values = someHashMap.entrySet()
                            .stream()
                            .filter(e -> something.contains(e.getKey()))
                            .map(Map.Entry::getValue)
                            .collect(Collectors.toList());

Upvotes: 6

Related Questions