I have a Map<Key1, Map<Key2, CustomObject>>
. I need go through the Map
, check if Key2.equals("a string")
and return a Map<Key1, CustomObject>
.
Is this possible with java 8? Should it be done with java 8 or is it better with nested for loops?
You can filter the entries of the input Map
to keep only entries whose value contains the "a string" key. Then use Collectors.toMap
to collect them into a new Map
:
Map<Key1, CustomObject> map =
inputMap.entrySet()
.stream()
.filter(e -> e.getValue().containsKey("a string"))
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().get("a string")));
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