Why do we need List to sort using Collection.sort() method?
问题 I am planning to sort keys from a hashmap. I am using a customized sort method. Following code gives me compile-time error on compareTo() method where I am using Set as Collection Set<String> set = map.keySet(); Collections.sort(set, (a, b) -> map.get(a) == map.get(b) ? a.compareTo(b) : map.get(b) - map.get(a)); If I convert Set to List and then sort then everything works fine . List<String> words = new ArrayList<>(map.keySet()); Collections.sort(words, (a, b) -> map.get(a) == map.get(b) ? a