hotels.stream().sorted(Comparator.comparing(Hotel::getCity)
.thenComparing(hotel -> hotel.getName().toUpperCase())))
.collect(Collectors.toList());
May I ask if there is a more concise way to write .thenComparing(hotel -> hotel.getName().toUpperCase())
, I've found a String.CASE_INSENSITIVE_ORDER
but how do I use this comparator on hotel.getName()
.
update: Applied @Arnaud Denoyelle 's suggestion.
hotels.stream().sorted(Comparator.comparing(Hotel::getCity)
.thenComparing(Hotel::getName, String.CASE_INSENSITIVE_ORDER))
.collect(Collectors.toList());
It looks better.
String.CASE_INSENSITIVE_ORDER
is a Comparator<String>
but you are trying to compare some Hotel
.
You can get a Comparator<Hotel>
like this :
// Map hotel to a String then use the Comparator<String>
Comparator.comparing(Hotel::getName, String.CASE_INSENSITIVE_ORDER);
Then, if you only need to sort, you don't need to use a Stream
, you can sort directly :
hotels.sort(Comparator.comparing(Hotel::getName, String.CASE_INSENSITIVE_ORDER));
So, with the first comparison criteria, the code becomes :
hotels.sort(
Comparator.comparing(Hotel::getCity)
.thenComparing(Hotel::getName, String.CASE_INSENSITIVE_ORDER)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With