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?
You could solve that using
Collectors.toMap
as :or a further complex one liner grouping and sum as :