Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch max value in a list of objects which are inside list of objects by month using Java Stream

I have list of Store objects and each Store object has a list of Sales objects. I want to fetch the Store object which has the highest sale for any item for a particular month.

public class Store {
 private String storeName;
 private String contactInfo;
 private List<Sales> sales;

//getter & setter
}
public class Sales {
 private String month;
 private String year;
 private BigInteger price;

//getter & setter
}

As of now I’m able to filter the list of Store objects by month

List<Store> stores = list.stream()
             .filter(s -> s.getPrice().stream().anyMatch(t -> t.getMonth().contains("Jan")))
             .collect(Collections.toList());

But I want to filter this list further to get a single store object which has the max price for the month of January.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT :
sample list structure in JSON format

[
   {
      "storeName": "abc",
      "contactInfo": "xcb",
      "sales": [{
                  "month" : "Jan",
                  "year": "2022",
                  "price": 3000
                },
                {
                  "month" : "Feb",
                  "year": "2022",
                  "price": 3300
                }
               ]
   },
   {
      "storeName": "abcde",
      "contactInfo": "xcbe",
      "sales": [{
                  "month" : "Jan",
                  "year": "2022",
                  "price": 2000
                },
                {
                  "month" : "Feb",
                  "year": "2022",
                  "price": 4000
                }
               ]
   }
] 

Thank you!

>Solution :

You can flat map to pairs of (store, price) and select the max:

stores.stream()
        .flatMap(store -> store.getSales()
                .stream()
                .filter(sales -> sales.getMonth().contains("Jan"))
                .map(sales -> Map.entry(store, sales.getPrice())))
        .max(Entry.comparingByValue())
        .map(Entry::getKey)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading