排序后返回哈希映射键列表?

我尝试对哈希图进行排序并返回结果键列表。这是我试过的:


public List<City> getCities() {


Map<Node<City>, Edge> map = new HashMap<>();


// add entries to map ...


return map.entrySet().stream()

            .sorted(Map.Entry.<Node<City>, Edge>comparingByValue())

            .map(e -> e.getKey().getValue())

            .collect(Collectors.toList());


}

边缘实现可兼容,getValue() 方法将返回一个 City 对象。


public class Edge<T> implements Comparable<Edge<T>> {


private Node<T> a;

private Node<T> b;


private double weight;


public Edge(Node<T> a, Node<T> b) {

    this.a = a;

    this.b = b;

}


public void setWeight(double weight) {

    this.weight = weight;

}


public double getWeight() {

    return sum;

}


@Override

public int compareTo(Edge<T> o) {

    return Double.compare(getWeight(), o.getWeight());

}


}

现在我的 IDE 没有抱怨任何东西,但是当我编译时我得到这个错误:


错误:(104, 28) java: 找不到符号符号:方法 getKey() 位置:java.lang.Object 类型的变量 e


我知道只发布一些代码和一个错误是不好的。但实际上我搜索了一个小时,一无所获。同样对我来说,代码绝对有意义,我不知道为什么无法识别条目的 getKey。


那么发生了什么?为什么我会收到此错误?


ITMISS
浏览 140回答 2
2回答

摇曳的蔷薇

我很确定您的班级Edge正在通过以下方式实施 Comparable:class Edge implements Comparable将您的类边缘声明更改为:class Edge implements Comparable<Edge>或者通过以下方式拆分您的返回逻辑:Stream<Map.Entry<Node<City>, Edge>> sorted = map.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .sorted(Map.Entry.comparingByValue());return sorted&nbsp; &nbsp; &nbsp; &nbsp; .map(e -> e.getKey().getValue())&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());问题是由于泛型对链式调用的类型推断。这可能会给你更多的细节。

幕布斯6054654

我没有你的课程,但我相信这就是你想要的。&nbsp; &nbsp; &nbsp; Map<String, Integer> map = Map.of("Z", 10, "X", 8, "Y", 9);&nbsp; &nbsp; &nbsp; // add entries to map ...&nbsp; &nbsp; &nbsp; List<String> keys = map.entrySet().stream().sorted(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Comparator.comparing(e -> e.getValue())).map(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e -> e.getKey()).collect(Collectors.toList());&nbsp; &nbsp; &nbsp; System.out.println(keys);在你的例子中,.map(e -> e.getKey().getValue())应该是 .map(e ->e.getKey())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java