0
List<String> list2 = Arrays.asList("hello", "hi", "你好");  
List<String> list3 = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");  

List<Stream<String>> list2Result = list2.stream().map(item -> list3.stream().map(item2 -> item + " " + item2)).collect(Collectors.toList());

list2Result.forEach(item -> item.collect(Collectors.toList()));
list2Result.forEach(item -> item.forEach(System.out::println));

I have to convert list2Result to List<List<String>>, but I can't used foreach to print it.

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed at java.util.stream.AbstractPipeline.evaluate(Unknown Source) at java.util.stream.ReferencePipeline.forEach(Unknown Source) at com.singhand.proxyServer.Main.lambda$15(Main.java:61) at java.util.ArrayList.forEach(Unknown Source) at com.singhand.proxyServer.Main.main(Main.java:61)

Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
xielei
  • 1
  • 3

1 Answers1

1

You cannot operate the same Stream twice.

Try to collect the list in the first map.

List<List<String>> list2Result = list2.stream()
        .map(item -> list3.stream()
            .map(item2 -> item + " " + item2)
            .collect(Collectors.toList()))
        .collect(Collectors.toList());

And print the list of lists in the same way

list2Result.forEach(item -> item.forEach(System.out::println));

If you want a flatten list, try to collect the list using before a flatMap which flats multiple streams in one.

List<String> list2Result = list2.stream()
        .map(item -> list3.stream()
            .flatMap(item2 -> item + " " + item2))
        .collect(Collectors.toList());

And then you will have the List of strings that can be printed.

list2Result.forEach(System.out::println);
Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34