![](/img/trans.png)
[英]How to sort List<Map<String,String>> by key1 descending order and key2 ascending order if key1 has same values
[英]How to use group-1 result key1 in group-2 when use Java Lambda like Map<key1, Map<key2, List<Obj>>>
Java Lambda如何在分組2中使用分組1。
這個問題是我解決的問題的更新: 如何使用Java lambda隱式將List映射到Map <T,<K,List <Person >>>?
您可以看到最后的代碼。 函數key2要使用函數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;
})));
您可以使用函數apply(T t)
。 根據javadoc :
將此函數應用於給定參數。
在您的情況下,這意味着:
int key1Result = key1.apply(p)
編輯 :在您修改問題時,我添加了一個答案,如果我理解您想做什么,那應該是正確的:
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
更多信息,請參見atomic 。 基本上,它是一個包裝程序 ,它將在線程之間保留其變量。
首先,您使用修改后的密鑰收集所需的地圖
Map<Integer, Map<Integer, List<Person>>> collect2 = personList.stream().collect(Collectors
.groupingBy(p -> p.getAge() * new Random(10).nextInt(),
Collectors.groupingBy(Person::getCityCode)));
然后更改地圖。 在這種情況下,問題是您正在使用嵌套地圖。 並利用key
要外地圖的change the key of inner Map
。 因此,除了為每個外部Key創建一個新的內部Map之外,您別無其他方法。
在這里,我要遍歷外部地圖的每個條目,並使用已經存在的內部地圖創建一個新的適當的(必需的)內部地圖。
collect2.entrySet().stream().forEach(e -> {
Integer key = e.getKey();
Map<Integer, List<Person>> oldValueMap = e.getValue();
Map<Integer, List<Person>> newValueMap = new HashMap<>();
oldValueMap.keySet().forEach(k -> {
newValueMap.put(k + key, oldValueMap.get(k));
});
e.setValue(newValueMap);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.