Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java stream sort with string comparator ignoring case [duplicate]

Tags:

java

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.

like image 547
Cosaic Avatar asked Aug 02 '18 14:08

Cosaic


1 Answers

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)
)
like image 93
Arnaud Denoyelle Avatar answered Sep 20 '22 21:09

Arnaud Denoyelle