首页 > 解决方案 > 转换 ArrayList> 到数组列表>

问题描述

我一直在尝试转换字符串ArrayList<ArrayList<String>> to ArrayList<ArrayList<Integer>>

这是我尝试构建的代码。

public void convertString (ArrayList<ArrayList<String>> templist) {
    readList = new ArrayList<ArrayList<Integer>> ();
    for (ArrayList<String> t : templist) {
        readList.add(Integer.parseInt(t));
    }
    return readList;

需要一些关于如何转换它的建议。非常感谢。

标签: javaarraylist

解决方案


您可以使用 Stream API 实现此目的:

ArrayList<ArrayList<String>> list = ...

List<List<Integer>> result = list.stream()
    .map(l -> l.stream().map(Integer::parseInt).collect(Collectors.toList()))
    .collect(Collectors.toList());

或者如果你真的需要ArrayList而不是List

ArrayList<ArrayList<String>> list = ...

ArrayList<ArrayList<Integer>> result = list.stream()
  .map(l -> l.stream().map(Integer::parseInt).collect(Collectors.toCollection(ArrayList::new)))
  .collect(Collectors.toCollection(ArrayList::new));

推荐阅读