Collect complex objects in one lambda expression

2020-03-26 05:47发布

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));

Result list must contains only 3 new coin objects:

Coin("USD", 1 , 216)
Coin("USD", 2 , 200)
Coin("CAD", 1 , 333)

How can this be written only in one lambda expression?

1条回答
SAY GOODBYE
2楼-- · 2020-03-26 06:48

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());
}
查看更多
登录 后发表回答