我尝试解析一个文本文件,其中的行如下所示:
@KEY,_,0,1,2,_,4,5,6, ...
@KEY
只是开头的标识符,而以下数字是我想要存储在 ArrayList<Integer>
中的数据.
我有一个元数据类,其中包含我想在其中插入整数的数组列表:
class MetaD {
public List<Integer> key1, key2, key3 = new ArrayList<Integer>();
}
我逐行解析文本文件;当该行以 @KEY
开头时,我想将元素添加到 key1
列表。如果有_
,应将其替换为空值:
if(line.startsWith("@KEY")){
metaObject.key1 = Arrays.asList(line.replace("@KEY,", "").replace("_", "").trim().split("\\s*,\\s*"));
}
我发现这不适用于 ArrayList<Integer>
。 key1
类型必须为 ArrayList<String>
或ArrayList<Object>
使其发挥作用。
有没有办法以同样的方式转换整数? 如果没有,我的想法如下:
- 将所有内容转换为
ArrayList<String>
- 迭代这个新的每一项
ArrayList
并将其转换为Integer.parseInt()
转换为整数。 - 将此新整数添加到我的
ArrayList<Integer>
是否有更有效或更好的方法来满足我的需求?
编辑: 由于 Tunaki 在评论中写道,我的想法可能是我尝试执行以下操作的唯一可能方法:
if(line.startsWith("@KEY")){
List<String> channelTemp = Arrays.asList(line.replace("@KEY,", "").replace("_", "1").split("\\s*,\\s*"));
channelTemp.forEach(item -> metaObject.channel.add(Integer.parseInt(item)));
System.out.println("done");
}
不幸的是,这会抛出 NullPointerException
在第三行,我不知道为什么。我替换了_
与 1
用于测试目的以避免NumberFormatException
。当我打印 lambda 函数中的每个对象而不是将它们添加到我的 ArrayList<Integer>
中时,我可以看到所有项目都有一个整数值。那么为什么我会在这里遇到异常呢?
最佳答案
既然你快到了,我会帮你的。
String line = "@KEY,_,0,1,2 , _,4,5,6,";
List<Integer> collect = Arrays.stream(line.replaceAll("@KEY|_", "").split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(Integer::valueOf).collect(Collectors.toList());
System.out.println(collect);
编辑
要获取null
,您可以更改映射过程,例如:
List<Integer> collect = Arrays.stream(line.split(","))
.skip(line.startsWith("@KEY") ? 1 : 0)
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(s -> "_".equals(s) ? null : Integer.valueOf(s)).collect(Collectors.toList());
关于java - 如何在 Java 中将整数字符串转换为 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32936353/