如何处理Java流中的额外值?
我有以下两个对象如何处理Java流中的额外值?,java,lambda,java-stream,Java,Lambda,Java Stream,我有以下两个对象 Product ProductInventory -type -Product -price -quantity -country 我需要通过遍历ProductInventory列表找到最便宜的。步骤如下: 如果product.type==input\u type和quantity>input\u quantity totalPrice=product.price*输入数量 如果country!=输入国
Product ProductInventory
-type -Product
-price -quantity
-country
我需要通过遍历ProductInventory
列表找到最便宜的。步骤如下:
product.type==input\u type
和quantity>input\u quantity
totalPrice=product.price*输入数量
country!=输入国家/地区
然后总价=总价+输入税
totalPrice
从最小值到最大值对记录进行排序我无法确定如何处理步骤2,其中我需要生成总价,但如何在流中创建和使用此字段?使用
ProductInventory
中声明的totalPrice
字段,您可以执行以下操作
private Optional<FinalEntity> doLogic(String inputCountry, String inputType, Integer inputQuantity, Integer inputTax) {
return Stream.of(new Inventory(new Product("cola", 15), "germany", 1000))
.filter(inv -> inv.getProduct().getType().equals(inputType) && inv.getQuantity() > inputQuantity)
.peek(inv -> {
Integer tax = inv.getCountry().equals(inputCountry) ? 0 : inputTax;
inv.setTotalPrice((inv.getProduct().getPrice() * inputQuantity) + tax);
})
.sorted(Comparator.comparing(Inventory::getTotalPrice))
.findFirst()
.map(Util::mapToFinalEntity);
}
及
结果值可以是一个可选的.empty()
,也可以是最终实体格式的结果值,我跳过了上一个映射到新对象(国家、剩余数量、总价)
,这是一个简单的步骤
如果您不希望在
Inventory
中有此字段,可以在其上创建一个包装类,包含totalPrice
,并从流开头的库存映射到它。您有totalPrice
值,该值不能存储在任何位置,为什么不将该值添加到ProductInventory
?是否使用了包装器类?还是直接插入到库存类中?我想把它插入包装类,因为正如你所知道的,产品清单有不同的用途。为什么不使用<代码> MAP>代码>而不是设计的<代码> PEEK ?@ Apple可以使用一个地图,认为可能有重复的密钥,你必须考虑这样的情况。问题是要有一个带有totalPrice值lambda解决方案的单一流,我的回答是,如果流
中的对象发生变异,则需要使用peek
的apophis。在这种情况下,使用map
会破坏方法的契约并导致UB。
public class Product {
String type;
Integer price;
// getters, setters, constructors
}
public class Inventory {
Product product;
String country;
Integer quantity;
Integer totalPrice;
// getters, setters, and constructors
}