gpt4 book ai didi

Java 8 - 在字符串流上不同 - IllegalStateException

转载 作者:行者123 更新时间:2023-11-29 09:47:04 24 4
gpt4 key购买 nike

<分区>

我对 Stringstream 执行不同的操作有问题。

Stream<String> names = Arrays.asList("NAME A", "NAME B", "NAME A").stream();
names.distinct();
System.out.println(names.collect(Collectors.joining(",")));

然后,我收到异常:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.Test.main(Test.java:62)

但是如果我这样写这部分代码:

Stream<String> names = Arrays.asList("NAME A", "NAME B", "NAME A").stream();
final Stream<String> distinct = names.distinct();
System.out.println(distinct.collect(Collectors.joining(",")));

一切正常

不同的文档说:

Stream distinct() Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream. For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.) For unordered streams, no stability guarantees are made. This is a stateful intermediate operation.

我做错了什么?

感谢帮助

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com