[英]How to convert List of List String into List of List Integer in java
我有一個List of List字符串,現在我想將其轉換為List Integer列表。 提出一些建議,如何進行?
這是我的代碼:
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();
}
}
}
我建議為此使用Streams API:
import static java.util.stream.Collectors.toList;
...
integerList = outerList.stream()
.map(innerList->innerList.stream().map(Integer::valueOf).collect(toList()))
.collect(toList());
您只需嘗試這樣:
for(String s : yourStringList)
{
intList.add(Integer.valueOf(s));
}
編輯
for (List<String> s : yourStringList) {
List<Integer> x = new ArrayList<Integer>();
for (String str: s) {
x.add(Integer.parseInt(str));
}
intList.add(x);
}
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);
}
您將必須遍歷每個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.