简体   繁体   中英

Best way to add all elements in an int array into a priority queue in Java

I have an int array and I need to create a priority queue from it.

currently I have:

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

Is there any other choice that might be better?

You can do it in one statement using Java 8 Stream. Whether that is "better" is a matter of opinion.

For comparison, here they are side-by-side:

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));

If costs had been an Integer[] , it would be different:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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