Java 8流:遍历列表地图

11

我有以下的对象和一个地图:

MyObject
    String name;
    Long priority;
    foo bar;

Map<String, List<MyObject>> anotherHashMap;

我想将一个Map转换为另一个Map。结果Map的键是输入Map的键。结果Map的值是My对象的"名字"属性,按优先级排序。

提取名称和排序不是问题,但我无法将其放入结果Map中。我是用旧的Java 7方式做的,但如果可以使用流API则更好。

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

    teaserPerPage.put(identifier, generatedList);
}

有人有想法吗?我尝试了这个,但卡住了:

anotherHashMap.entrySet().stream().collect(Collectors.asMap(..., ...));

意图不明确。你能解释一下你想做什么吗? - Olivier Meurice
1
这个解释更好吗? - waXve
你的结果映射值应该是什么?是前一个键中每个“name”的列表吗? - mkobit
3个回答

13
Map<String, List<String>> result = anotherHashMap
    .entrySet().stream()                    // Stream over entry set
    .collect(Collectors.toMap(              // Collect final result map
        Map.Entry::getKey,                  // Key mapping is the same
        e -> e.getValue().stream()          // Stream over list
            .sorted(Comparator.comparingLong(MyObject::getPriority)) // Sort by priority
            .map(MyObject::getName)         // Apply mapping to MyObject
            .collect(Collectors.toList()))  // Collect mapping into list
        );

基本上,您需要在每个条目集上进行流处理,并将其收集到新的映射中。要计算新映射中的值,您需要在旧映射中的List<MyOjbect>上进行流处理、排序并应用映射和收集函数。在这种情况下,我使用MyObject::getName作为映射,并将结果名称收集到列表中。


2
生成另一张地图,我们可以使用以下方式:
HashMap<String, List<String>> result = anotherHashMap.entrySet().stream().collect(Collectors.toMap(elem -> elem.getKey(), elem -> elem.getValue() // can further process it);

我正在重新创建地图,但您可以根据您的需求处理键或值。


我相信应该是.stream().collect。此外,您需要映射MyObject列表,类似于elem -> elem.getValue().stream().map(e -> e.name) - Giovanni Botta
忘记加 entrySet().stream() 了,已经修复 :) - nitishagar

2
Map<String, List<String>> result = anotherHashMap.entrySet().stream().collect(Collectors.toMap(
    Map.Entry::getKey,
    e -> e.getValue().stream()
        .sorted(comparing(MyObject::getPriority))
        .map(MyObject::getName)
        .collect(Collectors.toList())));

与Mike Kobit的答案相似,但排序是在正确的地方进行的(即按值排序,而不是按映射条目排序),并且使用更简洁的静态方法Comparator.comparing来获取用于排序的比较器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接