首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将ArrayList<ArrayList<String>>转换为ArrayList<ArrayList<Integer>>

将ArrayList<ArrayList<String>>转换为ArrayList<ArrayList<Integer>>
EN

Stack Overflow用户
提问于 2020-01-03 00:42:44
回答 4查看 88关注 0票数 2

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

以下是我尝试构建的代码。

代码语言:javascript
复制
public void convertString (ArrayList<ArrayList<String>> templist) {
    readList = new ArrayList<ArrayList<Integer>> ();
    for (ArrayList<String> t : templist) {
        readList.add(Integer.parseInt(t));
    }
    return readList;

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

EN

回答 4

Stack Overflow用户

发布于 2020-01-03 00:48:00

您可以使用Stream API来实现:

代码语言:javascript
复制
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

代码语言:javascript
复制
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));
票数 5
EN

Stack Overflow用户

发布于 2020-01-03 00:48:27

如果您使用的是Java-8,则可以使用:

代码语言:javascript
复制
public ArrayList<ArrayList<Integer>> convertString(ArrayList<ArrayList<String>> templist) {
    return templist.stream()
            .map(l -> l.stream()
                    .map(Integer::valueOf)
                    .collect(Collectors.toCollection(ArrayList::new)))
            .collect(Collectors.toCollection(ArrayList::new));
}

我建议使用List而不是ArrayList

代码语言:javascript
复制
public List<List<Integer>> convertString(List<List<String>> templist) {
    return templist.stream()
            .map(l -> l.stream()
                    .map(Integer::valueOf)
                    .collect(Collectors.toList()))
            .collect(Collectors.toList());
}
票数 4
EN

Stack Overflow用户

发布于 2020-01-03 00:47:20

您有嵌套的列表,因此需要一个嵌套的for循环。

代码语言:javascript
复制
for (ArrayList<String> t: tempList) {
    ArrayList<Integer> a = new ArrayList<>();
    for (String s: t) {
        a.add(Integer.parseInt(s));
    }
    readList.add(a);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59566928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档