0

I want to find max product from the list of Products(nested)

public class Product {
     private String id;
     private String name;
     private String status;
     private String parentId;
     private AdditionalEntity additionalEntity;

}

public class AdditionalEntity {

    private String storagePlan;
}

I want to get the max product based on storage plan and the value of storagePlan can be null, 100hrs, 150hrs, 300hrs, 500hrs. The storage plan can have duplicates like two products having the same hours (1500hrs). In that case, we can return any of the product(having 1500hrs). AdditionalEntity can also be null.

0

2 Answers 2

1
Optional<Product> max = listOfProducts.stream()
            .filter(product -> product.getAdditionalEntity() != null 
                    && product.getAdditionalEntity().getStoragePlan() != null)
            .max(Comparator.comparingInt(product -> 
                    Integer.valueOf(product.getAdditionalEntity().getStoragePlan())));

The filter filters any Product objects that has a null AdditionalEntity or null StoragePlan. We pass a Comparator to the max method. It compares the storage plan value as integer.

The result is an Optional Product that has the highest storage plan.

Sign up to request clarification or add additional context in comments.

1 Comment

works like a charm . just added null check on product and converted the storage plan to int .. removing the extra hrs in the suffix before converting to int
0

First of all you have to select a number from storagePlane, because this is a String. You can use either separate int value or extract it directly from String.

// e.g. like this; it's just example of product -> int
ToIntFunction<Product> hours = product -> Integer.parseInt(product.getAdditionalEntity().getStoragePlan().substring(0, 4));

And then very simple for loop:

Product maxProduct = null;

for (Product product : products)
    if (maxProduct == null || hours.applyAsInt(maxProduct) < hours.applyAsInt(product))
        maxProduct = product;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.