2

我正在使用 aList<Pair<String, Integer>>并根据键和值进行排序,但它显示以下错误为non-static method getKey() cannot be referenced from a static context

我的代码如下 -

import javafx.util.Pair;
import java.util.*;
class Tuple
{
    // Demonstrate javafx.util.Pair class introduced in Java 8
    public static void main(String[] args)
    {
        List<Pair<String, Integer>> entries = new ArrayList<>();

        entries.add(new Pair<String,Integer>("C", 20));
        entries.add(new Pair<>("C++", 10));
        entries.add(new Pair<>("Java", 30));
        entries.add(new Pair<>("Python", 10));
        entries.add(new Pair<>("PHP", 20));
        entries.add(new Pair<>("PHP", 10));

        // Comparator<Pair<String,Integer>> c=Comparator.<Pair<String,Integer>>comparing(e->e.getKey).thenComparingInt(Pair::getValue;
        //entries.sort(c.reversed());
        // Comparator<Pair<String,Integer>> c=Comparator.<Pair<String,Integer>>comparing(e->e.getKey).thenComparingInt(Pair::getValue);
        entries.sort(Comparator.<Pair<String,Integer>>comparing(Pair::getKey).thenComparingInt(Pair::getValue));
        entries.forEach(e->System.out.println(e.getKey()+" "+e.getValue()));

    }
}


4

3 回答 3

1

比较使用Pair<String,Integer>::getKey

entries.sort(Comparator.comparing(Pair<String,Integer>::getKey) .thenComparingInt(Pair::getValue))
于 2019-10-15T06:38:15.317 回答
1

Comparator::comparing接受两个通用参数TU

static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> var0)

你正在通过一个。第一个参数是您要比较的对象的类型,第二个参数是您要比较的属性。尝试这个 :

Comparator<Pair<String, Integer>> pairComparator = Comparator.<Pair<String, Integer>, String>comparing(Pair::getKey).thenComparingInt(Pair::getValue);
entries.sort(pairComparator);

而且我不鼓励Pair为此目的使用 JavaFX 类形式AbstractMap.SimpleEntry,例如:

public static void main(String[] args) {
        List<AbstractMap.SimpleEntry<String, Integer>> entries = new ArrayList<>();

        entries.add(new AbstractMap.SimpleEntry<String, Integer>("C", 20));
        entries.add(new AbstractMap.SimpleEntry<>("C++", 10));
        //...

        Comparator<AbstractMap.SimpleEntry<String, Integer>> simpleEntryComparator = Comparator.<AbstractMap.SimpleEntry<String, Integer>, String>comparing(AbstractMap.Entry::getKey).thenComparingInt(AbstractMap.SimpleEntry::getValue);
        entries.sort(simpleEntryComparator);
        entries.forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
}
于 2019-10-15T06:38:38.097 回答
1

您有 2 个问题:

  1. entries.sort(Comparator.<Pair<String, Integer>>comparing(您只指定了一种 Generci 类型,而预期是两种类型,即您的可比较对象类型和键类型。在这种情况下缺少密钥类型。

  2. 您没有Type::getKey正确指定泛型。在那里指定泛型类型或使用 lambda 表达式。

示例,下面带有 lambda 表达式和正确的泛型类型:

 entries.sort(Comparator.<Pair<String, Integer>, String>comparing(p -> p.getKey()).thenComparingInt(Pair::getValue));

您可以将JOOL库用于元组类型。它是对 java-8 的扩展支持。

于 2019-10-15T06:43:47.977 回答