gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:31:55 26 4
gpt4 key购买 nike

我有一个 Java 字符串列表,如下所示:

我的列表:

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

最佳答案

在 Java 8 中你可以使用流:

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);
}

结果是:

26366
10025
10026
10244
26595
26594
9026
9027
9029
9080
26597
10223
10287
10277
10215
10242
10243
9025
9030
9034
9051
9052
9055
10241
10067

关于java - 过滤 Java 列表并创建整型常量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37352341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com