Java “如何修复”;流已被操作或关闭”;嵌套映射函数出错

Java “如何修复”;流已被操作或关闭”;嵌套映射函数出错,java,java-stream,Java,Java Stream,我在尝试对两个流执行函数并生成一个输出时遇到了“流已经被操作或关闭” 我已经尝试过使用StreamSupplier,但似乎它并没有解决问题,如果我将两个流都转换为字符串列表并执行嵌套循环,问题就解决了。但是我想看看这个问题的流解决方案是什么 我现在的代码是 String[]str1=新字符串[]{“A”、“B”、“C”}; 字符串[]str2=新字符串[]{“a”、“b”、“c”}; 私有流方法(最终流str1, 最终流(str2){ 返回str1 .flatMap(s1->str2 .map(

我在尝试对两个流执行函数并生成一个输出时遇到了“流已经被操作或关闭”

我已经尝试过使用StreamSupplier,但似乎它并没有解决问题,如果我将两个流都转换为字符串列表并执行嵌套循环,问题就解决了。但是我想看看这个问题的流解决方案是什么

我现在的代码是

String[]str1=新字符串[]{“A”、“B”、“C”};
字符串[]str2=新字符串[]{“a”、“b”、“c”};
私有流方法(最终流str1,
最终流(str2){
返回str1
.flatMap(s1->str2
.map(s2->simpleStringConcatFunction_1(s1)+simpleStringConcatFunction_2(s2));
假设s1是一个3元素的字符串列表,也是s2。输出应该是一个9元素的字符串列表。 像

Aa,, Ab, 交流电, 文学士, Bb, 公元前, Ca, Cb, 抄送

我使用了双循环,实现了这些代码

专用流生成器模式(最终流str1,
最终流(str2){
List list1=str1.collect(Collectors.toList());
List list2=str2.collect(Collectors.toList());
列表=新的ArrayList();
for(字符串s1:list1){
for(字符串s2:list2){
添加(simpleStringConcatFunction_1(s1)+simpleStringConcatFunction_2(s2);
}
}
返回list.stream();
}

做非流式代码的一半,即拍摄
str2
的快照,这样您就可以对其进行多次流式处理:

List<String> list2 = str2.collect(Collectors.toList());
return str1.flatMap(s1 -> list2.stream()
                               .map(s2 -> simpleStringConcatFunction_1(s1) +
                                          simpleStringConcatFunction_2(s2)));
List list2=str2.collect(Collectors.toList());
返回str1.flatMap(s1->list2.stream()
.map(s2->simpleStringConcatFunction_1(s1)+
simpleStringConcatFunction_2(s2));

您可以使用两个流和一个
平面图来实现输出,以组合实际结果

public static void main(String[] args) {
    String[] str1 = new String[]{"A","B","C"};
    String[] str2 = new String[]{"a","b","c"};

    // The internal for
    Function<String, Stream<String>> combinationStream = str1Element -> Arrays.stream(str2)
            .map(str2Element -> str1Element.toUpperCase() + str2Element.toLowerCase());

    // The external for
    List<String> result = Arrays.stream(str1)
            .flatMap(combinationStream)
            .collect(Collectors.toList());

    System.out.println(result);
}
publicstaticvoidmain(字符串[]args){
字符串[]str1=新字符串[]{“A”、“B”、“C”};
字符串[]str2=新字符串[]{“a”、“b”、“c”};
//内部
函数组合stream=str1元素->数组.stream(str2)
.map(str2Element->str1Element.toUpperCase()+str2Element.toLowerCase());
//外部的
列表结果=Arrays.stream(str1)
.flatMap(组合流)
.collect(Collectors.toList());
系统输出打印项次(结果);
}
输出

[Aa、Ab、Ac、Ba、Bb、Bc、Ca、Cb、Cc]

我不确定你所说的“我已经试过使用StreamSupplier”是什么意思。实际的解决方案是,你不能只使用
str2
,但你必须传入一些可以为
str2
创建新流的内容。这不是真的。