Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 streams: iterate over Map of Lists

I have the following Object and a Map:

MyObject
    String name;
    Long priority;
    foo bar;

Map<String, List<MyObject>> anotherHashMap;

I want to convert the Map in another Map. The Key of the result map is the key of the input map. The value of the result map ist the Property "name" of My object, ordered by priority.

The ordering and extracting the name is not the problem, but I could not put it into the result map. I do it the old Java 7 way, but it would be nice it is possible to use the streaming API.

Map<String, List<String>> result = new HashMap<>();
for (String identifier : anotherHashMap.keySet()) {
    List<String> generatedList = anotherHashMap.get(identifier).stream()...;

    teaserPerPage.put(identifier, generatedList);
}

Has anyone an idea? I tried this, but got stuck:

anotherHashMap.entrySet().stream().collect(Collectors.asMap(..., ...));
like image 656
waXve Avatar asked Dec 12 '14 16:12

waXve


1 Answers

For generating another map, we can have something like following:

HashMap<String, List<String>> result = anotherHashMap.entrySet().stream().collect(Collectors.toMap(elem -> elem.getKey(), elem -> elem.getValue() // can further process it);

Above I am recreating the map again, but you can process the key or the value according to your needs.

like image 138
nitishagar Avatar answered Oct 06 '22 17:10

nitishagar