1.報錯内容
2.分析,根據報錯原因分析,出現錯誤的的地方是26行
這個異常表示stream流已經被使用或者關閉。
jdk8種的stream流是不可複用的,使用一次後就會被關閉,二次使用必須重新建立stream流。
源代碼:
@Test
public void Test() {
Stream<String> stream = Stream.of("hello", "world", "helloworld");
// 使用方法引用來傳遞行為, 更加清晰易懂, new(建立) -> add(累加) -> addAll(合并)
List<String> list2 = stream.collect(LinkedList::new, LinkedList::add, LinkedList::addAll);
String concat = stream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
System.out.println(list2);
System.out.println(concat);
}
解決方法,再建立一個stream流即可。如下所示:
public void Test() {
Stream stream = Stream.of(“hello”, “world”, “helloworld”);
// 使用方法引用來傳遞行為, 更加清晰易懂, new(建立) -> add(累加) -> addAll(合并)
List list2 = stream.collect(LinkedList::new, LinkedList::add, LinkedList::addAll);
System.out.println(list2);
Stream stream2= Stream.of(“hello”, “world”, “helloworld”);
String concat = stream2.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
System.out.println(concat);
}
輸出: