问题描述
目前我有:
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));
如果 costs
是 Integer[]
,情况会有所不同:
Integer[] costs = new Integer[] {1,6};
PriorityQueue<Integer> pq = new PriorityQueue<>(Arrays.asList(costs));