例如:我有一个Set,其中包含两个或多个Product实例对象(“它们具有不同的数量值”)
public class Product{
private int id;
private String name;
private String brand;
private Long amount;
// getter and setters
}
是否可以使用Stream获得一个对象并求和金额值?
假设您有一个Set<Product>
位置,其中每个产品的ID,名称和品牌相同,但数量不同。我们可以很容易地创建一个新的Product
,但是用一个创建一个Stream
是多余的(reduce
也许可以使用,但是可能比下面的创建更多的开销)。相反,让我们为您的问题创建一个空集安全的解决方案:
public Product getTotalAsProduct(Set<Product> set) {
Product newProduct = null;
Optional<Product> findProduct = set.stream().findFirst();
if(findProduct.isPresent()) { //No sense in making an object if set is empty
//Create a new Product with the same id, name, brand
newProduct = findProduct.get().clone(); //If Cloneable, OR create a constructor that takes a Product and makes a new one, OR make a new Product() and get/set as needed
long totalAmount = set.stream().mapToInt(Product::getAmount).sum();
newProduct.setAmount(totalAmount);
}
return newProduct; //Null if set was empty
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句