Stream列表触发IllegalStateException及List<List<String>>转换需求
Alright, let's get to the bottom of your issue. That IllegalStateException is popping up because Streams can only be consumed once—once you run a terminal operation like collect() or forEach() on a Stream, it's closed and can't be reused.
In your original code, you first call item.collect(Collectors.toList()) on each Stream in list2Result, which uses up the Stream entirely. Then when you try to call item.forEach(System.out::println) right after, you're trying to access an already-consumed Stream, hence the exception.
Plus, your end goal is a List<List<String>>, so we don't need to store Streams at all—we can convert each inner Stream to a List directly during the initial stream processing.
Here's the fixed code:
List<String> list2 = Arrays.asList("hello", "hi", "你好"); List<String> list3 = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu"); // Directly collect inner streams to List, resulting in List<List<String>> List<List<String>> list2Result = list2.stream() .map(item -> list3.stream() .map(item2 -> item + " " + item2) .collect(Collectors.toList())) // Convert inner Stream to List immediately .collect(Collectors.toList()); // Now safely iterate and print all elements list2Result.forEach(subList -> subList.forEach(System.out::println));
Why this works:
- No more reused Streams: We convert each inner Stream (from
list3.stream()) to aList<String>right away usingcollect(Collectors.toList()), so we never store a Stream in our final collection. - Matches your target type: The outer stream now emits
List<String>elements, so collecting it gives us exactly theList<List<String>>you need. - Cleaner iteration: Since we're working with a list of lists, we can iterate directly without worrying about consumed Streams.
A quick side note: Arrays.asList() returns a fixed-size list. If you need to modify these lists later (add/remove elements), wrap them in an ArrayList like new ArrayList<>(Arrays.asList(...))—but that's optional depending on your use case.
内容的提问来源于stack exchange,提问作者xielei

