本文介绍了在一个lambda表达式中收集复杂对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象列表。首先,我需要按类型对其进行排序。
比faceValue。最后,总结所有数量:
I have a list of objects. At first, I need to sort it by type.Than by faceValue. In the end, summarize all quantities:
class Coin{
String type;
BigInteger faceValue;
BigInteger quantity;
...
}
List<Coin> coins = new ArrayList<>();
coins.add(new Coin("USD", 1, 150));
coins.add(new Coin("USD", 1, 6));
coins.add(new Coin("USD", 1, 60));
coins.add(new Coin("USD", 2, 100));
coins.add(new Coin("USD", 2, 100));
coins.add(new Coin("CAD", 1, 111));
coins.add(new Coin("CAD", 1, 222));
结果列表必须只包含3个新的硬币对象:
Result list must contains only 3 new coin objects:
Coin("USD", 1 , 216)
Coin("USD", 2 , 200)
Coin("CAD", 1 , 333)
如何仅在一个lambda表达式中编写?
How can this be written only in one lambda expression?
推荐答案
您可以使用 Collectors.toMap
解决这个问题:
You could solve that using Collectors.toMap
as :
public List<Coin> groupedCoins(List<Coin> coins) {
return new ArrayList<>(
coins.stream()
.collect(Collectors.toMap(
coin -> Arrays.asList(coin.getType(), coin.getFaceValue()), Function.identity(),
(coin1, coin2) -> {
BigInteger netQ = coin1.getQuantity().add(coin2.getQuantity());
return new Coin(coin1.getType(), coin1.getFaceValue(), netQ);
}))
.values());
}
或更复杂的一个班轮分组和总和:
or a further complex one liner grouping and sum as :
public List<Coin> groupedAndSummedCoins(List<Coin> coins) {
return coins.stream()
.collect(Collectors.groupingBy(Coin::getType,
Collectors.groupingBy(Coin::getFaceValue,
Collectors.reducing(BigInteger.ZERO, Coin::getQuantity, BigInteger::add))))
.entrySet()
.stream()
.flatMap(e -> e.getValue().entrySet().stream()
.map(a -> new Coin(e.getKey(), a.getKey(), a.getValue())))
.collect(Collectors.toList());
}
这篇关于在一个lambda表达式中收集复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!