gpt4 book ai didi

java - 如何使用 java lambda 将 List 转换为 Map>>?

转载 作者:行者123 更新时间:2023-12-02 09:55:28 29 4
gpt4 key购买 nike

如何将列表转换为Map<Integer, Map<Integer, List<Person>>>使用java lambda?

我只知道这个:

private static Map<Dish.Type, List<String>> groupDishNamesByType() {
return menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, toList())));
}

我只知道这个:

 public static <T, F> Map<F, T> listToMap(List<T> list, Function<T, F> f) {
return list.stream().collect(Collectors.toMap(f, obj -> obj));
}

但是我不知道如何编写use Map作为Map中的键。可能:

class Person{
int age;
int cityCode;
String name;
}

method:

// Map<age, Map<cityCode, List<Person>>>
public Map<Integer, Map<Integer, List<Person>>> covertListToMap(List<Person> list){

// TODO: How to make List<Person> to Map<age, Map<cityCode, List<Person>>>

}


Thank you floor-1 @Master chief.
But now I found the other problem:
When the build first group's key , get a key1result, I want to use it in second group, How to do it? -_-


Function<Person, Integer> key1 = (Person p) -> {
// do many sth then get a key1Result:
int key1Result = p.getAge() * new Random(10).nextInt();
return key1Result;
};

Function<Person, Integer> key2 = (Person p) -> {
// Question: how to get and use Function key1 key1Result:

int key1Result = 0;

int result = p.getCityCode() + key1Result;
return result;
};

Map<Integer, Map<Integer, List<Person>>> collect = list.stream().collect(groupingBy(key1, groupingBy(key2)));

最佳答案

Map<Integer, Map<Integer, List<Person>>> collect = personList.stream().collect(Collectors
.groupingBy(Person::getAge, Collectors.groupingBy(Person::getCityCode)));

关于java - 如何使用 java lambda 将 List 转换为 Map<T, <K, List<Person>>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56038542/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com