[英]How to convert List of List String into List of List Integer in java
I have a List of List string, now I want to convert it into List of List Integer. 我有一个List of List字符串,现在我想将其转换为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();
}
}
}
I woud suggest using the Streams API for this: 我建议为此使用Streams API:
import static java.util.stream.Collectors.toList;
...
integerList = outerList.stream()
.map(innerList->innerList.stream().map(Integer::valueOf).collect(toList()))
.collect(toList());
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);
}
res is new arrayList contains lists of integers. res是新的arrayList包含整数列表。
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);
}
You will have to iterate over each subItem
of each item
. 您将必须遍历每个item
每个subItem
。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.