本文介绍了转换列表<人>映射到Map< Integer,List< Integer>>.使用Lambdas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表转换为Map,如下所示.这是示例.

I wanted to convert list to Map as below. Here is the example.

我有一个学生列表,类似于下面的代码片段.使用Key作为Integer来获取Hasmap,它的Age和Value作为List.

I have student list something like below code snippet. Get a Hasmap out of it with Key as Integer which is Age and value as List.

在下面的输入提要中,我的答复应类似于以下内容.我该如何实现?

From the below input feed, My response should be something like below. How do I achieve this ?

地图[[10,{1}],[20,{2,3,4}],[30,{5}]. [40,{6}]];

Map[[10, {1}], [20, {2,3,4}], [30,{5}]. [40,{6}]];

private static List<Person> getPersonTestData() {
    List<Person> personList = new ArrayList<>();
    personList.add(Person.of(1, "First1", "Last1", 10));
    personList.add(Person.of(2, "First2", "Last2", 20));
    personList.add(Person.of(3, "First3", "Last3", 20));
    personList.add(Person.of(4, "First4", "Last4", 20));
    personList.add(Person.of(5, "First5", "Last5", 30));
    personList.add(Person.of(6, "First6", "Last6", 40));

    return personList;
}

在此先感谢.......!

Thanks In Advance.......!

推荐答案

您可以在下游使用groupingBymapping来做到这一点:

You can do it using groupingBy and mapping in the downstream as :

Map<Integer, List<Integer>> ageToIdsMap = getPersonTestData().stream()
        .collect(Collectors.groupingBy(Person::getAge,
                Collectors.mapping(Person::getId, Collectors.toList())));

这篇关于转换列表&lt;人&gt;映射到Map&lt; Integer,List&lt; Integer&gt;&gt;.使用Lambdas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:48