Felipe Marcelo :
according to a product list with these example values
new Product("A", new Stock(5));
new Product("B", new Stock(1));
new Product("A", new Stock(1));
I would like to filter the list of duplicate objects and if there is a duplicate object. I subtract the values from it in the list.
//list after filter
Product A = 4 stock
B = 1 stock
is it possible to do this with stream?
Deadpool :
You can use Collectors.toMap with mergeFunction, and in the merge function you can define the logic to subtract
Collection<Product> result = products.stream()
.collect(Collectors.toMap(Product::getName, Function.identity(), (p1, p2) -> {
int count = p1.getStock().getValue() - p2.getStock().getValue();
p1.getStock().setValue(count > 0 ? count : 0);
return p1;
})).values();
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=295398&siteId=1