如何对 <Entry<Character, Integer>> 类型的 ArrayList 进行排序?

How to sort an ArrayList of type <Entry<Character, Integer>>?

我有一个名为 map 的 HashMap,它将字符存储为键,将整数存储为值,然后使用以下代码将其存储到名为 entries 的 ArrayList 中:

Set<Entry<Character, Integer>> s = map.entrySet();
ArrayList<Entry<Character, Integer>> entries = new ArrayList<>(s);

现在我尝试根据整数值而不是键对这些条目进行排序。我尝试使用 lambda 表达式来实现 Comparator 接口,但它不起作用。这是我的代码:

Collections.sort(sortedEntries, (sortedEntries.get(0), sortedEntries.get(1)) -> { 
    sortedEntries.get(0).getValue().compareTo(sortedEntries.get(1).getValue())
});

这些是我得到的错误:

Multiple markers at this line

  • Syntax error, insert ")" to complete Expression

  • The method sort(List, Comparator) in the type Collections is not applicable for the arguments (ArrayList>, Map.Entry, Map.Entry)

  • Syntax error on token "->", ; expected

您可以按以下方式对列表进行排序:

list.sort(Comparator.comparing(Entry::getValue));

您可以使用 Java 流 API 对实体进行排序,如下所示:

Set<Entry<Character, Integer>> s = map.entrySet();
List<Entry<Character, Integer>>  sortedEntries = s.stream()
            .sorted((a, b)-> Integer.compare(a.getValue(), b.getValue()))
            .collect(Collectors.toList());

这完全符合您的代码,请参阅

Collections.sort(sortedEntries, (Entry<Character,Integer> o1, Entry<Character,Integer> o2)-> {return o1.getValue().compareTo(o2.getValue());}); 

地图、列表或您要排序的类型没有什么特别之处。您对此类列表进行排序的方式与对元素类型未实现 Comparable 的任何 List 进行排序的方式相同 - 通过使用 Comparator,就像您尝试做的那样。所以你在正确的轨道上。

如果您对 lambda 表达式不满意,也许可以尝试实现 Comparator 接口。类型系统将强制您 "do it right",而不是依靠您来正确地为您推断类型。

(我在这里使用条目的键,但您也可以使用值)

public class EntryKeyComparator implements Comparator<Entry<Character,Integer>> {
    @Override
    public int compare(Entry<Character,Integer> a, Entry<Character,Integer> b) {
        return a.getKey().compareTo(b.getKey());
    }
}

现在,如果你真的想使用lambda表达式,你只需要看看这个实现中的compare方法。 lambda 表达式必须有两个参数,ab,而且它必须 return 一个 int。因此,你会得到类似的东西:

Collections.sort(list, (a, b) -> a.getKey().compareTo(b.getKey()));

但是既然你已经在Java8的世界里,你还不如使用List接口上的staticcomparing() method on the Comparator class. It takes as argument a Function that extracts the key you want to use to compare the elements by. In my examples, I've compared the entries by their keys via the getKey(). We can reference this method with the :: operator, so you end up with an expression like this (using the new sort()方法:

list.sort(Comparator.comparing(Entry::getKey));