当使用Java Lambda(如Map <key1,Map <key2,List< Obj>>)时如何在group-2中使用group-1结果key1. [英] How to use group-1 result key1 in group-2 when use Java Lambda like Map<key1, Map<key2, List<Obj>>>
问题描述
如何使用Java Lambda在group-2中使用group-1结果.
How to use group-1 result in group-2 by Java Lambda.
这个问题是我解决的问题的更新: 如何隐蔽列表到地图< T,< ; K,List< Person>>使用Java Lambda吗?
This question is update from my a solved problem: How to covert List to Map<T, <K, List<Person>>> use java lambda?
您可以看到最后的代码. 函数key2要使用函数key1的结果,该怎么做?
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;
})));
推荐答案
您可以使用函数apply(T t)
.根据 javadoc :
You can use the function apply(T t)
. According to the javadoc:
将此函数应用于给定参数.
Applies this function to the given argument.
对于您而言,这意味着:
In your case, it would mean:
int key1Result = key1.apply(p)
编辑:在您修改问题时,我添加了一个答案,如果我理解您想做的事,那应该是正确的:
Edit: As you modified your question, I add an answer, should be right if I understood what you wanted to do:
AtomicInteger atomicInteger = new AtomicInteger(0);
Map<Integer, Map<Integer, List<Person>>> collect = personList.stream().collect(Collectors
.groupingBy(p -> {
int age = p.getAge() * new Random(10).nextInt();
atomicInteger.set(age);
return age;
}, Collectors.groupingBy(p2 -> p2.getCityCode() + atomicInteger.get())));
如果您想了解有关AtomicInteger
的更多信息,请参见
If you want to read more about AtomicInteger
, see atomic. Basically it is a wrapper that will keep its variable between threads.
这篇关于当使用Java Lambda(如Map <key1,Map <key2,List< Obj>>)时如何在group-2中使用group-1结果key1.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!