How to use group-1 result in group-2 by Java Lambda.
This question is update from my a solved problem: How to covert List to Map<T, <K, List<Person>>> use java lambda?
you can see the last code. the function key2 want to use function key1's result, how to do it?
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)));
I write a wrong sample to show my meaning:
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;
})));