Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Streams filter Map based on a list of keys

I have a particular problem and was wondering whether the Java 8 Streams API could solve it. I know that this can be done outside of using Streams API but I don't want to add all the boilerplate code associated with trying to achieve that, if it can be done using Streams. I have a map

Map<String, String> greetings = new HashMap<>();
greetings.put("abc", "Hello");
greetings.put("def", "Goodbye");
greetings.put("ghi", "Ciao");
greetings.put("xyz", "Bonsoir");

and a list of keys:

List<String> keys = Arrays.asList("def", "zxy");

and using the above with Streams API, is it possible to filter that down to:

Map<String, String> filteredGreetings = new HashMap<>();
filteredGreetings.put("def", "Goodbye");
filteredGreetings.put("xyz", "Bonsoir");

Hopefully this makes sense what I am trying to achieve.

So far I have got this to work only when specifying the exact key which to filter the map's keySet on, but then this would only return a single entry set. I am interested in a completely filtered down map and I am struggling to achieve that.

like image 480
Richard C Avatar asked Mar 03 '23 20:03

Richard C


1 Answers

If the input and the expected output in the question is not a typo, you can also retain the keys of the input map as:

Map<String, String> futureGreetings = new HashMap<>(greetings);
futureGreetings.keySet().retainAll(keys);
like image 162
Naman Avatar answered Mar 11 '23 22:03

Naman