Java 8 流:迭代列表映射

Java 8 streams: iterate over Map of Lists(Java 8 流:迭代列表映射)
本文介绍了Java 8 流:迭代列表映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象和地图:

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.

ordering 和提取名称不是问题,但我无法将其放入结果图中.我用旧的 Java 7 方式来做,但如果可以使用流式 API,那就太好了.

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

推荐答案

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 作为映射并将生成的名称收集到一个列表中.

Essentially, you stream over each entry set and collect it into a new map. To compute the value in the new map, you stream over the List<MyOjbect> from the old map, sort, and apply a mapping and collection function to it. In this case I used MyObject::getName as the mapping and collected the resulting names into a list.

这篇关于Java 8 流:迭代列表映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)