Search code examples
javalistjava-streamgroup

How to group and count items in a List using the Java stream API


I have the following OrderItems class:

public class OrderItems {
    public int id;
    public double portion;
}

and the following List<OrderItems>:

List<OrderItems> orderItems = new ArrayList<>();
orderItems.add(new OrderItems(1,0.5));
orderItems.add(new OrderItems(2,1));
orderItems.add(new OrderItems(1,0.5));
orderItems.add(new OrderItems(1,1.5));
orderItems.add(new OrderItems(2,1));
orderItems.add(new OrderItems(2,0.5));

How can I group this list and convert to the following NewOrderItems class with the stream API?

public class NewOrderItems {
   public int id;
   public double portion;
   public long amount;
}

The result should be like this:

NewOrderItems{id=1, portion=0.5, amount=2}
NewOrderItems{id=1, portion=1.5, amount=1}
NewOrderItems{id=2, portion=0.5, amount=1}
NewOrderItems{id=2, portion=1.0, amount=2}

Solution

  • My solution like this :

    Map<Integer, Map<Double, Long>> collect = orderItems.stream()
                        .collect(Collectors.groupingBy(OrderItems::getId, Collectors.groupingBy(OrderItems::getPortion, Collectors.counting())));
                System.out.println(collect);
    
                List<NewOrderItems> newOrderItems = new ArrayList<>();
    
                collect.forEach((k,v)->{
                        v.forEach((x,y)->{
                               NewOrderItems newOrderitems=new NewOrderItems(k,x,y);
                               newOrderItems.add(newOrderitems);
                        });
                });
                newOrderItems.forEach(System.out::println);
    

    Console:

    NewItems{id=1, portion=0.5, amount=2}
    NewItems{id=1, portion=1.5, amount=1}
    NewItems{id=2, portion=0.5, amount=1}
    NewItems{id=2, portion=1.0, amount=2}