在一个lambda表达式中收集复杂对象

编程入门 行业动态 更新时间:2024-10-22 04:57:35
本文介绍了在一个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表达式中收集复杂对象

本文发布于:2023-11-28 15:32:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642970.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   对象   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!