如何自定义PriorityQueue.stream().foreach以优先级顺序进行迭代

编程入门 行业动态 更新时间:2024-10-26 02:26:21
本文介绍了如何自定义PriorityQueue.stream().foreach以优先级顺序进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有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以优先级顺序进行迭代

本文发布于:2023-10-29 07:45:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539126.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:优先级   自定义   顺序   迭代   foreach

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!