简体   繁体   English

转换 ArrayList <ArrayList<String> &gt; 到 ArrayList <ArrayList<Integer> &gt;

[英]Converting ArrayList<ArrayList<String>> to ArrayList<ArrayList<Integer>>

I have been trying to convert string of ArrayList<ArrayList<String>> to ArrayList<ArrayList<Integer>>我一直在尝试将ArrayList<ArrayList<String>> to ArrayList<ArrayList<Integer>>字符串转换ArrayList<ArrayList<String>> to ArrayList<ArrayList<Integer>>

Here is my codes that I tried to build.这是我尝试构建的代码。

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

Need some advice on how to convert it.需要一些关于如何转换它的建议。 Thanks a lot.非常感谢。

You can achieve this using Stream API:您可以使用 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());

Or if you really need ArrayList and not List :或者,如果您确实需要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));

If you are using Java-8 you can use :如果您使用的是 Java-8,则可以使用:

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));
}

I would suggest to use List instead of ArrayList :我建议使用List而不是ArrayList

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());
}

You have nested lists so you will need a nested for-loop.您有嵌套列表,因此您将需要一个嵌套的 for 循环。

for (ArrayList<String> t: tempList) {
    ArrayList<Integer> a = new ArrayList<>();
    for (String s: t) {
        a.add(Integer.parseInt(s));
    }
    readList.add(a);
}

With java-8, you do it as below,使用 java-8,您可以按如下方式进行,

templist.stream()
        .map(l->l.stream().map(Integer::valueOf).collect(Collectors.toList()))
        .collect(Collectors.toList());

This would be List<List<Integer> .这将是List<List<Integer> If you want ArrayList you can use,如果你想要ArrayList你可以使用,

Collectors.toCollection(ArrayList::new)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM