Sort list of objects in java

I have a class

public class ProductStock {

   private Long id;
   private Integer quantity;

}

and list for example

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, for example below.

productStocks = 
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}
+4
source share
4 answers

I would do this:

Map<Long, Integer> counting = productStocks.stream().collect(
                Collectors.groupingBy(ProductStock::getId, Collectors.counting()));

Create a new map with the id key and Count as value.

+2
source

With Java8 threads, you can try this as follows:

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

What does it do:

  • productStocks.stream().collect( Collectors.toMap(...) ) creates a stream for the list and collects values ​​on the map.
  • p -> p.id uses product identifier as card key
  • p -> p uses the product as a map value if it does not already exist
  • (p,o) -> { p.quantity += o.quantity; return p;} p "" o, p . Product: (p,o) -> new Product(p.id, p.quantity + o.quantity)
  • ,

, . , , 4- collect(...): LinkedHashMap::new.

+2

Map ProductStock . Map, List of ProductStock, .

Map<Long, Long> productStockMap = productStocks.stream().collect(Collectors.groupingBy(ProductStock::getId, Collectors.counting()));
productStocks = new ArrayList<>();
for(Map.Entry<Long, Long> entry: productStockMap.entrySet()) {
    productStocks.add(new ProductStock(entry.getKey(), entry.getValue().intValue()));
}

:

============Before============

ProductStock{id=1, quantity=1}
ProductStock{id=2, quantity=1}
ProductStock{id=3, quantity=1}
ProductStock{id=1, quantity=1}
ProductStock{id=4, quantity=1}
ProductStock{id=5, quantity=1}
ProductStock{id=2, quantity=1}

=============After============

ProductStock{id=1, quantity=2}
ProductStock{id=2, quantity=2}
ProductStock{id=3, quantity=1}
ProductStock{id=4, quantity=1}
ProductStock{id=5, quantity=1}
+1

LinkedHashMap :

void mergeProducts() {
    Map<Long, Integer> pMap = new HashMap<Long, Integer>();
    for (ProductStock ps :  productStocks) {
        if (pMap.containsKey(ps.getId())) {
            int qty = pMap.get(ps.getId());
            qty += ps.getQuantity();
            pMap.put(ps.getId(), qty);
        } else {
            pMap.put(ps.getId(), ps.getQuantity());
        }
    }

    System.out.println("Product grouping: ");
    for (Map.Entry<Long, Integer> entry : pMap.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}
0

Source: https://habr.com/ru/post/1689378/


All Articles