如何在 Java 中创建一个空的 Stream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42252681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:02:14 来源:igfitidea点击:
How do I create an empty Stream in Java?
提问by sdgfsdh
In C# I would use Enumerable.Empty()
, but how do I create an empty Stream
in Java?
在 C# 中,我会使用Enumerable.Empty()
,但如何Stream
在 Java 中创建一个空的?
采纳答案by Eugene
As simple as this: Stream.empty()
就这么简单: Stream.empty()
回答by prasad_
Stream<String> emptyStr = Stream.of();
emptyStr.count()
returns 0 (zero).
emptyStr.count()
返回 0(零)。
In addition:
此外:
- For a primitive stream like
IntStream
,IntStream.of()
works in similar way (also theempty
method).IntStream.of(new int[]{})
also returns an empty stream. - The
Arrays
class has stream creation methods which accept an array of primitives or an object type. This can be used to create an empty stream; e.g.,:System.out.println(Arrays.stream(new int[]{}).count());
prints zero. - Any stream created from a collection (like a
List
orSet
) with zero elements can return an empty stream; for example:new ArrayList<Integer>().stream()
returns an empty stream of typeInteger
.
- 对于像 一样的原始流
IntStream
,IntStream.of()
以类似的方式工作(也是empty
方法)。IntStream.of(new int[]{})
还返回一个空流。 - 所述
Arrays
类具有接受原语的阵列或一个对象类型的流创建方法。这可用于创建一个空流;例如:System.out.println(Arrays.stream(new int[]{}).count());
打印零。 - 从具有零元素的集合(如 a
List
或Set
)创建的任何流都可以返回空流;例如:new ArrayList<Integer>().stream()
返回类型为 的空流Integer
。