2

I have been trying to convert string of 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.

boonboon93
  • 41
  • 4
  • Also, keep in mind when converting a String to an Integer "you'll notice the "catch" is that this function can throw a NumberFormatException" https://stackoverflow.com/a/5585800/4977223 – Christophe Douy Jan 02 '20 at 16:50

4 Answers4

5

You can achieve this using 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<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));
Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
3

You have nested lists so you will need a nested for-loop.

for (ArrayList<String> t: tempList) {
    ArrayList<Integer> a = new ArrayList<>();
    for (String s: t) {
        a.add(Integer.parseInt(s));
    }
    readList.add(a);
}
Faron
  • 1,354
  • 10
  • 23
3

If you are using Java-8 you can use :

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 :

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());
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

With java-8, you do it as below,

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

This would be List<List<Integer>. If you want ArrayList you can use,

Collectors.toCollection(ArrayList::new)
Vikas
  • 6,868
  • 4
  • 27
  • 41