Reputation: 107
I have a List of List string, now I want to convert it into List of List Integer. Suggest some way, How to proceed for it?
here is my code:
public class convert {
public static void main(String[] args) {
try {
List<List<String>> outerList = new ArrayList<List<String>>();
outerList.add(new ArrayList<String>(asList("11","2")));
outerList.add(new ArrayList<String>(asList("2","1")));
outerList.add(new ArrayList<String>(asList("11","3")));
System.out.println(outerList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 302
Reputation:
You will have to iterate over each subItem
of each item
.
List<List<String>> stringList = new ArrayList<List<String>>(); // Input
List<List<Integer>> intList = new ArrayList<List<Integer>>(); // Output
for (List<String> item : stringList) {
List<Integer> temp = new ArrayList<Integer>();
for (String subItem : item) {
temp.add(Integer.parseInt(subItem));
}
intList.add(temp);
}
Upvotes: 1
Reputation: 172608
You simply try like this:
for(String s : yourStringList)
{
intList.add(Integer.valueOf(s));
}
EDIT
for (List<String> s : yourStringList) {
List<Integer> x = new ArrayList<Integer>();
for (String str: s) {
x.add(Integer.parseInt(str));
}
intList.add(x);
}
Upvotes: 3
Reputation: 200266
I woud suggest using the Streams API for this:
import static java.util.stream.Collectors.toList;
...
integerList = outerList.stream()
.map(innerList->innerList.stream().map(Integer::valueOf).collect(toList()))
.collect(toList());
Upvotes: 4
Reputation:
res is new arrayList contains lists of integers.
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(List<String> l : outerList){
ArrayList<Integer> al = new ArrayList<Integer>();
for(String s: l){
al.add(Integer.valueOf(s));
}
res.add(al);
}
Upvotes: 1