Reputation: 41
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.
Upvotes: 2
Views: 100
Reputation: 7175
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)
Upvotes: 2
Reputation: 13803
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));
Upvotes: 5
Reputation: 60026
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());
}
Upvotes: 3
Reputation: 1393
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);
}
Upvotes: 3