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)
}
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 keyp -> 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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With