【发布时间】:2019-05-08 11:46:44
【问题描述】:
Java Lambda 如何使用 group-1 生成 group-2。
这个问题是我解决的问题的更新: How to covert List to Map<T, <K, List<Person>>> use java lambda?
你可以看到最后的代码。 function key2 想使用 function key1 的结果,怎么办?
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>>>
}
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 = list.stream().collect(groupingBy((Person p) -> {
int key1Result = p.getAge() * new Random(10).nextInt();
return key1Result; // perhaps, now, key1Result is 10
}, groupingBy((Person p) -> {
// now, I want to get the key1Result which is 10, How to do it?
int key1Result = 0;
int result = p.getCityCode() + key1Result;
return result;
})));
【问题讨论】:
-
当你说Key2想使用key1的结果是什么意思?你能举个例子吗?
-
int key1Result = key1.apply(person)??? -
我更新我的问题以解释我在第三个代码区域的含义
-
也许不是嵌套 groupBys,而是尝试链接它们。
-
这里真正的问题是数组映射的映射