javaliststreamgroup

Grouping List<OrderItems> and counting


I have OrderItems class

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

and List<OrderItems> like below:

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));

My Question : How can i group this list and convert NewOrderItems class with Stream API:

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

Result should be like this:

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}

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}