Issue
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.
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)
Answered By - shmosel
Answer Checked By - Senaida (JavaFixing Volunteer)