Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to get a sub HashMap based on a list of Keys?

Tags:

java

hashmap

I have a HashMap and I would like to get a new HashMap that contains only the elements from the first HashMap where K belongs to a specific List.

I could look through all the keys and fillup a new HashMap but I was wondering if there is a more efficient way to do it?

thanks

like image 654
aregnier Avatar asked Mar 04 '15 14:03

aregnier


People also ask

How do you get all keys of a Map as a list in Java?

Use keySet() to Get a Set of Keys From a HashMap in Java The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap .

Can HashMap have list as key?

Yes you can have ArrayList s as a keys in a hash map, but it is a very bad idea since they are mutable. If you change the ArrayList in any way (or any of its elements), the mapping will basically be lost, since the key won't have the same hashCode as it had when it was inserted.

How do you compare two HashMaps by their keys?

We can check if two HashMap objects have the same keys by comparing their keys obtained using the keySet() method. We use equals() method of the set to compare keys.


1 Answers

With Java8 streams, there is a functional (elegant) solution. If keys is the list of keys to keep and map is the source Map.

keys.stream()     .filter(map::containsKey)     .collect(Collectors.toMap(Function.identity(), map::get)); 

Complete example:

    List<Integer> keys = new ArrayList<>();     keys.add(2);     keys.add(3);     keys.add(42); // this key is not in the map      Map<Integer, String> map = new HashMap<>();     map.put(1, "foo");     map.put(2, "bar");     map.put(3, "fizz");     map.put(4, "buz");      Map<Integer, String> res = keys.stream()         .filter(map::containsKey)         .collect(Collectors.toMap(Function.identity(), map::get));      System.out.println(res.toString()); 

Prints: {2=bar, 3=fizz}

EDIT add a filter for keys that are absent from the map

like image 62
T.Gounelle Avatar answered Sep 28 '22 17:09

T.Gounelle