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

在Kotlin中如何将List集合转换为ArrayList

转换方法(以Java场景为例,ArrayList为java.util.ArrayList实现)

你给出的是嵌套结构的List<List<Data>>类型数据,根据最终想要的结构不同,有两种常见转换方式:

1. 保留嵌套结构,内外层都转为ArrayList

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// 你的原始嵌套列表
List<List<Data>> originalList = List.of(
    List.of(new Data("name1", "good"), new Data("name2", "good")),
    List.of(new Data("name2", "good"), new Data("name2", "bad"))
);

// 写法1:普通循环实现
ArrayList<ArrayList<Data>> nestedArrayList = new ArrayList<>();
for (List<Data> inner : originalList) {
    nestedArrayList.add(new ArrayList<>(inner));
}

// 写法2:Java 8+ 流式写法
ArrayList<ArrayList<Data>> nestedArrayList = originalList.stream()
    .map(ArrayList::new)
    .collect(Collectors.toCollection(ArrayList::new));

2. 摊平嵌套结构,转为一维ArrayList

如果需要把所有Data元素放到同一个一维ArrayList里,用以下方法:

// 写法1:普通循环实现
ArrayList<Data> flatArrayList = new ArrayList<>();
for (List<Data> inner : originalList) {
    flatArrayList.addAll(inner);
}

// 写法2:Java 8+ 流式写法
ArrayList<Data> flatArrayList = originalList.stream()
    .flatMap(List::stream)
    .collect(Collectors.toCollection(ArrayList::new));

注意:示例中的Data类需要你确保有对应参数的构造方法,代码里的构造写法仅对齐你给出的示例结构。

内容的提问来源于stack exchange,提问作者sooyeon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:06:05