我有一个带有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(); 推荐答案您可以使用 Stream :: generate 和"> 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); }比较器是您的比较器.
在 Java 9 中,您可以使用 Stream :: takeWhile ,其谓词拒绝空值.因为当队列为空时, Queue :: poll 将返回 null -生成的 Stream 将按顺序包含队列中的元素(这是替代方法)如第一个解决方案所述使用 limit ):
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以优先级顺序进行迭代
发布评论