Stream APIを使用できます。使用Collectors.toMap
および使用AbstractMap.SimpleEntry
マップのキーとして。次に、同じキーの複数の値に対してマージ関数を定義します。
List<myPojo> res = new ArrayList<>(rows.stream()
.collect(Collectors.toMap(
e -> new AbstractMap.SimpleEntry<>(e.getName(), e.getCurrency()),
Function.identity(),
(a, b) -> new myPojo(a.getName(), a.getCurrency(), a.getAmount().add(b.getAmount()))))
.values());
デモ:
List<myPojo> list = new ArrayList<>();
list.add(new myPojo("A", "USD", new BigDecimal(1.0)));
list.add(new myPojo("A", "USD", new BigDecimal(2.0)));
list.add(new myPojo("A", "USD", new BigDecimal(3.0)));
list.add(new myPojo("B", "USD", new BigDecimal(1.0)));
list.add(new myPojo("B", "USD", new BigDecimal(2.0)));
list.add(new myPojo("B", "USD", new BigDecimal(3.0)));
list.add(new myPojo("A", "US", new BigDecimal(1.0)));
list.add(new myPojo("A", "US", new BigDecimal(2.0)));
list.add(new myPojo("A", "US", new BigDecimal(3.0)));
List<myPojo> res = new ArrayList<>(list.stream()
.collect(Collectors.toMap(
e -> new AbstractMap.SimpleEntry<>(e.getName(), e.getCurrency()),
Function.identity(),
(a, b) -> new myPojo(a.getName(), a.getCurrency(), a.getAmount().add(b.getAmount()))))
.values());
System.out.println(res.toString());
出力:
[myPojo [name=B, currency=USD, amount=6],
myPojo [name=A, currency=USD, amount=6],
myPojo [name=A, currency=US, amount=6]]
注:MyPojo
より良い規則のために、クラスの名前を大文字にするようにしてください
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加