Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stream a Map of String and Map using java 8?

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?

like image 922
Bobernac Alexandru Avatar asked Dec 18 '22 02:12

Bobernac Alexandru


1 Answers

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")));
like image 78
Eran Avatar answered Jan 17 '23 23:01

Eran