将 int 数组中的所有元素添加到 Java 中的优先级队列的最佳方法

问题描述

我有一个 int 数组,我需要从中创建一个优先级队列。

目前我有

int[] costs=new int[]{1,2,3,4,5,6};
PriorityQueue<Integer> pq=new PriorityQueue<>();
        
for(int cost:costs){
    pq.add(cost);
}

还有其他更好的选择吗?

解决方法

您可以使用 Java 8 Stream 在一个语句中完成。这是否“更好”是一个见仁见智的问题。

为了比较,这里并排:

int[] costs = new int[] {1,2,3,4,5,6};

// Java 5.0 or later
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int cost : costs)
    pq.add(cost);

// Java 8 or later
PriorityQueue<Integer> pq = Arrays.stream(costs).boxed()
        .collect(Collectors.toCollection(PriorityQueue::new));

如果 costsInteger[],情况会有所不同:

Integer[] costs = new Integer[] {1,6};

PriorityQueue<Integer> pq = new PriorityQueue<>(Arrays.asList(costs));

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...