prettyvoid prettyvoid - 1 year ago 75
Java Question

List stream, get items with lowest price

I have a

, each
have a
BigDecimal minSellingPrice
, I want to get the
with the minimum selling price.

I was able to achieve this via this code, h2) -> h1.getMinSellingPrice().compareTo(h2.getMinSellingPrice())).get()

But what if 3 hotels in the list have the minimum selling price in common, so the list have 50 hotels, lowest
is 100, 3 hotels out of 50 have a
of 100.

How can I get a list of those 3 hotels so I can operate on them? The only thing I thought of is getting the minimum price via
then querying the list for the items that have this lowest price, but that doesn't sound too nice.

Answer Source

Use the form of Collectors.groupingBy() that allows you to specify the type of Map to use, and specify a SortedMap or NavigableMap implementation. Then you can easily retrieve the collection of minimal elements from the result.

NavigableMap<BigDecimal, List<Hotel>> hotelByPrice =
    .collect(Collectors.groupingBy(Hotel::getMinSellingPrice, TreeMap::new, Collectors.toList()));
List<Hotel> cheapest = hotelByPrice.firstEntry().getValue();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download