Lambda – grouping and summing list items using java 8 streams

Suppose I have a list < banana > banana Banana class is defined as follows:

Banana. java

public class Banana{
   String name;
   Long weight;
   Long price;
   // getters & setters
}

The banana list contains:

[
   {"banana1",10,20},{"banana1",{"banana2",20,30},30,{"banana3",50,40},]

What I want to do here is to group bananas according to their names, including the sum weight column and & price column (each separately), so that I can get this result:

[
   {"banana1",60},]

Thank you in advance

resolvent

Solution

You can use the merge feature to combine them with collectors Tomap grouping:

Map<String,Banana> bananasByName =
    bananas.stream()
           .collect(Collectors.toMap(Banana::getName,Function.identity(),(b1,b2)->{ 
                                                 b1.addWeightAndPrice(b2); return b1; 
                                              }));

Where addweightandprice is the instance method of banana class, which adds the weight and price of the passed banana to the banana instance calling it

If you don't want to change the original banana instance, you can change the merge function to create a new banana instance and add two input banana instance weights and prices

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>