You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stream列表触发IllegalStateException及List<List<String>>转换需求

Fixing IllegalStateException & Converting to List<List>

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:

  1. No more reused Streams: We convert each inner Stream (from list3.stream()) to a List<String> right away using collect(Collectors.toList()), so we never store a Stream in our final collection.
  2. Matches your target type: The outer stream now emits List<String> elements, so collecting it gives us exactly the List<List<String>> you need.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:23:36