1つのラムダ式で収集複雑なオブジェクト

user3756506:

私は、オブジェクトのリストを持っています。最初は、私は種類によってそれをソートする必要があります。faceValueによってより。最後に、全ての量を要約したものです。

      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つの新しいコインオブジェクトが含まれています。

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

どのようにこれが唯一のラムダ式で記述することができますか?

また:

あなたは、使用していることを解決することができCollectors.toMapて:

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

または、さらに複雑なものライナーのグループ化と和として:

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=214096&siteId=1