我一直在尝试转换ArrayList<ArrayList<String>> to ArrayList<ArrayList<Integer>>字符串
以下是我尝试构建的代码。
public void convertString (ArrayList<ArrayList<String>> templist) {
readList = new ArrayList<ArrayList<Integer>> ();
for (ArrayList<String> t : templist) {
readList.add(Integer.parseInt(t));
}
return readList;需要一些关于如何转换它的建议。非常感谢。
发布于 2020-01-03 00:48:00
您可以使用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());或者如果你真的需要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));发布于 2020-01-03 00:48:27
如果您使用的是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));
}我建议使用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());
}发布于 2020-01-03 00:47:20
您有嵌套的列表,因此需要一个嵌套的for循环。
for (ArrayList<String> t: tempList) {
ArrayList<Integer> a = new ArrayList<>();
for (String s: t) {
a.add(Integer.parseInt(s));
}
readList.add(a);
}https://stackoverflow.com/questions/59566928
复制相似问题