如何从java中的嵌套对象列表中获取max对象
我想从列出的产品列表中查找max product如何从java中的嵌套对象列表中获取max对象,java,list,Java,List,我想从列出的产品列表中查找max product public class Product { private String id; private String name; private String status; private String parentId; private AdditionalEntity additionalEntity; } public class AdditionalEntity { priva
public class Product {
private String id;
private String name;
private String status;
private String parentId;
private AdditionalEntity additionalEntity;
}
public class AdditionalEntity {
private String storagePlan;
}
我想根据存储计划得到最大乘积,存储计划的值可以为null、100小时、150小时、300小时、500小时。存储计划可以有重复项,就像两个产品具有相同的小时数。在这种情况下,我们可以退回1500小时内的任何产品。AdditionalEntity也可以为null
过滤器过滤具有空AdditionalEntity或空StoragePlan的任何产品对象。我们将比较器传递给max方法。它将存储计划值作为整数进行比较
结果是一个具有最高存储计划的可选产品 首先,您必须从storagePlane中选择一个数字,因为这是一个字符串。您可以使用单独的int值,也可以直接从字符串中提取它
工作起来很有魅力。刚刚在产品上添加了空检查,并将存储计划转换为int。。在转换为int之前删除后缀中的额外hr
Optional<Product> max = listOfProducts.stream()
.filter(product -> product.getAdditionalEntity() != null
&& product.getAdditionalEntity().getStoragePlan() != null)
.max(Comparator.comparingInt(product ->
Integer.valueOf(product.getAdditionalEntity().getStoragePlan())));
// e.g. like this; it's just example of product -> int
ToIntFunction<Product> hours = product -> Integer.parseInt(product.getAdditionalEntity().getStoragePlan().substring(0, 4));
Product maxProduct = null;
for (Product product : products)
if (maxProduct == null || hours.applyAsInt(maxProduct) < hours.applyAsInt(product))
maxProduct = product;