java stream sort with string comparator ignoring case

  • A+
Category:Languages
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) ) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: