我有Java list of Strings
如下:
myList:
C26366
C10025, C10026
C10244
C26595
C26594
C9026, C9027, C9029, C9080 //this is one list element (needs seperation)
C26597
C10223, C10287, C10277, C10215
C10242
C10243
C9025, C9030, C9034, C9051, C9052, C9055 // similarly here
C10241
C10067
C27557
C10066
.... //these are all ids
以上是for-loop
代码段下方的输出:
for (String id: myList) {
System.out.println(id);
}
如何将此myList转换为Java整数数组?我期待/我想使用该数组作为:
public static final IDS = { 31598,9089,9092,9093,9108,9109,....}
IDS array
必须保留myList
中的内容,并且内容中没有C's
,也没有其他字符,只有数字。
答案 0 :(得分:2)
在Java 8中,您可以使用流:
int[] lines = new int[] {1, 2, 3};
session.EnableFilter("OnlyLinesWithNumbers").SetParameterList("LineNumbers", lines);
结果是:
List<String> myList = Arrays.asList(
"C26366", "C10025, C10026", "C10244", "C26595", "C26594",
"C9026, C9027, C9029, C9080", "C26597", "C10223, C10287, C10277, C10215",
"C10242", "C10243",
"C9025, C9030, C9034, C9051, C9052, C9055", "C10241", "C10067");
List<Integer> myListOfIntegers = myList.stream()
.map(x -> x.split(","))
.flatMap(l -> Arrays.asList(l).stream())
.map(y -> y.replaceAll("\\D", ""))
.map(z->Integer.parseInt(z))
.collect(Collectors.toList());
for( Integer i : myListOfIntegers ){
System.out.println(i);
}
答案 1 :(得分:1)
我建议这样做:
List<Integer> myListIntegers = new ArrayList<Integer>();
for (String subStrings : myList) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(subStrings);
while (m.find()) {
myListIntegers.add(Integer.parseInt(m.group()));
}
}
System.out.println(myListIntegers);
此代码将打印包含您在 myList
中的指针的列表[26366,10025,10026,10244,26595,26594,9026,9027,9029,9080, 10241,10067,27557,10066]