繁体   English   中英

排序一对<string,integer>在 Java</string,integer>

[英]Sorting a Pair<String,Integer> in Java

我正在使用List<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()));

    }
}


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

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

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

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

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

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

而且我不鼓励为此目的使用Pair class 形式 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()));
}

您有 2 个问题:

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

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

例如,下面使用 lambda 表达式和正确的泛型类型:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM