java stream sort with string comparator ignoring case

Cosaic :
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.

Arnaud Denoyelle :

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)
)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36166&siteId=1