Home > database >  Java Stream - Iterate list and inner list , sum up a value in the inner list and group by a key in t
Java Stream - Iterate list and inner list , sum up a value in the inner list and group by a key in t

Time:12-20

I have this data structure,

Order has a list of 'External', which inturn has 'Discount' list.

Order
External 1
    Discount 1 (discountCode 'discount1' , discountAmount 100)
    Discount 2 (discountCode 'discount2' , discountAmount 10)
External 2
    Discount 1 (discountCode 'discount1' , discountAmount 110)

Code Snipet

    External external1 = new External();
    Discount d1 = new Discount();
    d1.setDiscountAmount(100);
    d1.setDiscountCode("discount1");
    Discount d2 = new Discount();
    d2.setDiscountAmount(10);
    d2.setDiscountCode("discount2");
    external1.setDiscount(Arrays.asList(d1,d2));

    External external2 = new External();
    Discount d3 = new Discount();
    d3.setDiscountAmount(110);
    d3.setDiscountCode("discount1");
    external2.setDiscount(Arrays.asList(d3));

    Order order = new Order()
    order.setExternal(Arrays.asList(external1,external2));

I need to iterate 'External' list , group by 'discountCode' and sum up 'discountAmount' of all items in the 'External' list . Finally, would like to get result in a Map<String, Integer> like,
key discount1 value 210
key discount2 value 10

Using Stream , How could I iterate all elements in the list, group by discount code and sum up discount values?

CodePudding user response:

Firstly, you need to flatten the nested lists into a stream of Discount:

var discountStream = order.external().stream().flatMap(e -> e.discount().stream());

Now you can collect the stream into a map using an accumulator that sum the discount values of each discount code:

return discountStream.collect(Collectors.toMap(Discount::discountCode, Discount::discountAmount, (existing, replacement) -> existing   replacement));

Minimal working example

  • Related