如何对pair< string,integer>的列表进行排序?

flmtquvp  于 2021-07-13  发布在  Java
关注(0)|答案(4)|浏览(549)

我有一份commmons的清单 Pair 它存储单词及其频率,如下所示

private List<Pair<String, Integer>> words = new ArrayList<Pair<String, Integer>();

我试图对它进行排序,这样当我遍历它来打印单词时,我希望频率最高的单词首先出现。
我试着和他玩 Comparable 但大多数示例与使用成对列表不同

hwazgwia

hwazgwia1#

您可以使用自定义 Comparator :

Collections.sort(words, new Comparator<Pair<String, Integer>>() {
    @Override
    public int compare(final Pair<String, Integer> o1, final Pair<String, Integer> o2) {
        // TODO: implement your logic here
    }
});
xyhw6mcr

xyhw6mcr2#

按数字降序排列元素

Collections.sort(words, Comparator.comparing(p -> -p.getRight()));

这将按降序使用对中的“右”。
它使用Java8。从概念上讲,您正在装箱该值并使用integer.compareto。
但是,通过转义分析,可以消除装箱,并且您不能创建任何对象。

w80xi6nr

w80xi6nr3#

你好,我想这个应该适合你。

List<Pair<String, Integer>> words = new ArrayList<Pair<String, Integer>>();
    words.add(new Pair<String, Integer>("hello",2));
    words.add(new Pair<String, Integer>("hello",1));
    words.add(new Pair<String, Integer>("aello",3));

    words.sort(new Comparator<Pair<String, Integer>>() {
        @Override
        public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) {
            if (o1.getValue() > o2.getValue()) {
                return -1;
            } else if (o1.getValue().equals(o2.getValue())) {
                return 0; // You can change this to make it then look at the
                          //words alphabetical order
            } else {
                return 1;
            }
        }
    });

    System.out.println(words);
5m1hhzi4

5m1hhzi44#

将java 8 lambda与 Comparator.comparing (您还需要颠倒顺序):

import static java.util.Collections.reverseOrder;
import static java.util.Comparator.comparing;

final List<Pair<String, Integer>> words = new ArrayList<>();
final Comparator<Pair<String, Integer>> c = reverseOrder(comparing(Pair::getValue));
Collections.sort(words, c);

如果只想按频率降序打印值,最简单的方法是:

words.stream()
        .sorted(c)
        .map(Pair::getKey)
        .forEach(System.out::println);

相关问题