Convert a Queue to List

后端 未结 6 1174
Happy的楠姐
Happy的楠姐 2020-12-31 01:29

What is the fastest way to convert a Queue into a List while keeping the Queue order?

6条回答
  •  没有蜡笔的小新
    2020-12-31 01:53

    If you're converting from PriorityQueue to a List, remember that it is in fact a heap, so the ordering is determined using the poll() method, in which case, doing it by the constructor way as discussed in some of the other answers here, won't preserve the natural ordering of the queue.

    Taking that into consideration, you can go along these lines:

    List result = new ArrayList<>(yourPriorityQueue.size());
    while (!yourPriorityQueue.isEmpty()) {
        result.add(yourPriorityQueue.poll());
    }
    

提交回复
热议问题