问题
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