prettyvoid prettyvoid - 1 month ago 9
Java Question

List stream, get items with lowest price

I have a

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

I was able to achieve this via this code

hotels.stream().min((h1, 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
minSellingPrice
is 100, 3 hotels out of 50 have a
minSellingPrice
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
map
and
min
then querying the list for the items that have this lowest price, but that doesn't sound too nice.

Answer

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 = hotels.stream()
    .collect(Collectors.groupingBy(Hotel::getMinSellingPrice, TreeMap::new, Collectors.toList()));
List<Hotel> cheapest = hotelByPrice.firstEntry().getValue();