Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organize list of object in java

Tags:

java

I have a class

public class ProductStock {

   private Long id;
   private Integer quantity;

}

and a list like

List<ProductStock> productStocks = 
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}

I want to group productStocks by id. What is the best way to convert this list like bellow

productStocks = 
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}
like image 803
Md. Shougat Hossain Avatar asked Dec 13 '22 19:12

Md. Shougat Hossain


1 Answers

With Java8 streams you could try it like this:

productStocks = new ArrayList<>( productStocks.stream().collect( 
       Collectors.toMap( p -> p.id, p -> p, (p,o) -> { p.quantity += o.quantity; return p;} ) )
                 .values() );

What this does:

  • productStocks.stream().collect( Collectors.toMap(...) ) creates a stream for the list and collects the values into a map.
  • p -> p.id uses the product's id as the map key
  • p -> p uses the product as the map value, if it doesn't exist already
  • (p,o) -> { p.quantity += o.quantity; return p;} merges the existing product p and the "new" product value o by adding the quantity into p and returning that. Alternatively you could create a new Product instance: (p,o) -> new Product(p.id, p.quantity + o.quantity)
  • finally we build a new list out of the map's values

Note that collecting the elements into a map like like might not preserve the order of the elements. If you want to keep the order as defined in the source list, you could add a 4th parameter to collect(...): LinkedHashMap::new.

like image 185
Thomas Avatar answered Dec 16 '22 09:12

Thomas