过滤Java列表并创建整数常量数组

时间:2016-05-20 17:16:39

标签: java arrays string list int

我有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,也没有其他字符,只有数字。

2 个答案:

答案 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)

我建议这样做:

  1. 定义最终值的整数列表
  2. 然后使用正则表达式使用此模式&#34; \ d +&#34;在字符串列表中只查找数字
  3. 的内容
  4. 如果找到,将其解析为整数并将其添加到列表中。
  5. 实施例

    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]