如何自定义PriorityQueue.stream().foreach以优先级顺序进行迭代 [英] How to customize PriorityQueue.stream().foreach to iterate in priority order
问题描述
我有一个带有PriorityQueue字段的类:
I have a class with PriorityQueue field inside:
public class MyClass<T>{
Queue<T> queue = new PriorityQueue<>();
我想以某种方式从MyClass获取流并使用foreach,并希望序列按PriorityQueue的优先级顺序运行.最简单的方法是重写stream()方法:
I want somehow get a stream from MyClass and use foreach and want the sequence behave in priority order of my PriorityQueue. The easiest way is to override stream() method:
@Override
public Stream stream() {
return queue.stream();
}
,但这不会按优先级顺序显示队列元素.因此,问题是:如何使foreach流方法的行为类似于:
but this will not expose the queue element in priority order. So the question is: how to make foreach stream method behave like:
while(!queue.isEmpty())
queue.poll();
推荐答案
您可以使用"> Queue :: poll
方法来创建 Stream
,其中包含 PriorityQueue
中的元素并保持其顺序:
You could use Stream::generate
and Queue::poll
method to get create a Stream
with elements from PriorityQueue
with keeping their order:
@Override
public Stream<T> stream() {
return Stream.generate(queue::poll);
}
但是这可能很危险,因为 Stream :: generate
将不断调用 poll
,因此它可能是无限的Stream.因此,应考虑在队列大小中使用 Stream :: limit
:
However this might be dangerous because Stream::generate
will be invoking poll
constantly so it is potentially an inifinite Stream. Therfore using Stream::limit
with the queue size should be considered :
@Override
public Stream<T> stream() {
return Stream.generate(queue::poll)
.limit(queue.size());
}
或者您可以简单地返回已排序的流:
Or you could simply return sorted stream :
@Override
public Stream<T> stream() {
return queue.stream()
.sorted(comparator);
}
比较器是您的比较器.
In Java 9 you could use Stream::takeWhile
with predicate that rejects nulls. As Queue::poll
will return null
when queue is empty - the resulting Stream
will contain elements from the queue in their order (this is alternative to using limit
as described in the first solution) :
@Override
public Stream<T> stream() {
return Stream.generate(queue::poll)
.takeWhile(Objects::nonNull);
}
这篇关于如何自定义PriorityQueue.stream().foreach以优先级顺序进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!