Convert List<Person> to Map<Integer, List<Integer>> using Lambdas

可紊 提交于 2021-02-16 14:39:25

问题


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

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 ?

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.......!


回答1:


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


来源:https://stackoverflow.com/questions/54872793/convert-listperson-to-mapinteger-listinteger-using-lambdas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!