gpt4 book ai didi

java - 如何在执行一次操作后重用 Stream

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

我想使用相同的 Stream 找出以特定字符开头的 String 两次,但是第二个 Stream 操作抛出一个异常(exception)。如何重新使用 Stream

public static void main(String[] args) {
Stream<String> stream = Stream.of("abc", "aef", "bcd", "bef", "crf");
stream.filter(s -> s.startsWith("a")).forEach(System.out::println);;
stream.filter(s -> s.startsWith("b")).forEach(System.out::println);;
}

异常

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.<init>(Unknown Source)
at java.util.stream.ReferencePipeline.<init>(Unknown Source)
at java.util.stream.ReferencePipeline$StatelessOp.<init>(Unknown Source)
at java.util.stream.ReferencePipeline$2.<init>(Unknown Source)
at java.util.stream.ReferencePipeline.filter(Unknown Source)
at StreamExp.main(StreamExp.java:13)

最佳答案

您不能执行终端操作,例如 forEach两次相同 Stream .

您还有其他选择。例如,您可以生成 Map<Character,List<String>>其中输入String s 按第一个字符分组:

Map<Character,List<String>> groups = 
Stream.of("abc", "aef", "bcd", "bef", "crf")
.collect(Collectors.groupingBy(s->s.charAt(0)));

这将导致以下 Map :

{a=[abc, aef], b=[bcd, bef], c=[crf]}

关于java - 如何在执行一次操作后重用 Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39016328/

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