How to make Collections.sort without the thermal operator if
-
In folding code
Map<String, Integer >
Used it.Collections.sort
♪ The code works, sorts keys and values. But I was wondering how you could do the same sorting without the thermal operator? Is that possible?Collections.sort(list2, (o1, o2) -> o1.getValue()-o2.getValue() != 0 ? o1.getValue()-o2.getValue() : o2.getKey().compareTo(o1.getKey()) );
-
The use of differentiation when comparing whole numbers is not recommended to avoid overcrowding errors if, for example, values or keys
Integer.MIN_VALUE
andInteger.MAX_VALUE
♪So, a chain of comparators is being requested here to exclude therary operator:
Collections.sort(list2, Map.Entry.<Integer, Integer>comparingByValue() .thenComparing(Map.Entry::getKey, Comparator.reverseOrder()) );
Besides, starting with Java 8,
List
Method https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#sort(java.util.Comparator) to sort itself:list2.sort(Map.Entry.<Integer, Integer>comparingByValue() .thenComparing(Map.Entry::getKey, Comparator.reverseOrder()) );