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
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With