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.
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);
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