Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter the elements of a map based on a subset of its keys without iterating through the entire thing

I have a Map<String, ArrayList> and a Set<String>. Is there a way to "intersect" the keys of the map with the set of strings such that only the pairs with the given key remain, without iterating over the entire map? My main concern is performance and re-inventing the wheel on something that can be done more elegantly.

like image 894
dave Avatar asked Jul 18 '11 20:07

dave


People also ask

How do you filter a Map?

We can filter a Map in Java 8 by converting the map. entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.

How do you filter a Stream Map?

Few Java examples to show you how to filter a Map with Java 8 stream API. With Java 8, you can convert a Map. entrySet() into a stream , follow by a filter() and collect() it.


1 Answers

Just do:

map.keySet().retainAll(set); 

As per the javadoc, the changes in the key set are reflected back in the map.

... The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. ...

Here's a demo:

Map<String, String> map = new HashMap<String, String>(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three");  Set<String> set = new HashSet<String>(); set.add("1"); set.add("3");  map.keySet().retainAll(set);  System.out.println(map); // {3=three, 1=one} 
like image 99
BalusC Avatar answered Sep 22 '22 12:09

BalusC