2016-11-23 144 views
-1

我有一个HashMap中,其关键是距离和值是ArrayList中包含基于其在特定的距离(即密钥)优先级队列的ArrayList HashMap的

我要让HashMap中的优先级队列的顶点列表(优先级在键上)来获得一次处于特定距离的所有顶点。

是否有可能使这样的优先级队列(无界的)? 任何人都可以帮忙吗?

+0

这可能有助于https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html – cjungel

回答

1

您可以使用class来封装距离和顶点。实现Comparable接口或通过Comparator对象时,您将newPriorityQueue。你可以这样做以下...

class Node implements Comparable<Node> { 
    int distance; 
    List<Vertex> list; 

    public Node(int distance, List<Vertex> list) { 
    this.distance = distance; 
    this.list = list; 
    } 

    @Override 
    public int compareTo(Node o) { 

     // your compare logic goes here 
     return Integer.compare(this.distance, o.distance); 
    } 
} 

=====

public static void main(String[] args) { 

    PriorityQueue<Node> q = new PriorityQueue<>(); 

} 
0

的PriorityQueue是无界的,它的增长动态地根据在队列中的元素个数。它在任何时候都具有内部容量,并随着元素的添加而增加。

但是,在将其转换为PriorityQueue时,如果希望按键排序地图(即距离),则使用按距离排序的LinkedHashMap,但我没有看到太多意义。

Map<Double, List<Vertex>> map = new LinkedHashMap<>(); 
//... 
map = map.entrySet().stream() 
      .sorted(Map.Entry.comparingByKey()) 
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); 
+0

喜Zildyan谢谢...-我的要求是Dijkstra的一样。在迭代中选择最小距离顶点,并且放宽所选择的顶点的所有输出边以找到顶点的新距离。我想避免排序,因为我觉得这个要求在计算上花费很大。 – pkumar