gpt4 book ai didi

Java 8 & NIO/读取行 -> 收集到实体

转载 作者:行者123 更新时间:2023-12-01 07:25:52 24 4
gpt4 key购买 nike

需要逐行读取文本文件并解析每个文件以根据对象Entity成员的值进行设置。我的实体有下一个构造函数签名:

public Entity(int id, String name, double weight)

文本文件包含以下内容:

ID,NAME,WEIGHT
1,Mario,80.2
2,Marco,91.1
...
100,Diego,78.12

使用新的 Java 8:Files::readAllLines方法我的解决方案非常庞大:

public class CoolApp {

private static final String SOURCE_FILE = "path/to/txt/file/entities.txt";

private static final int ID = 0;
private static final int NAME = 1;
private static final int WEIGHT = 2;

public static void main(String[] args) throws Exception {
boolean isHeader = true;

List<Entity> entities = new ArrayList<>();

for (String line : Files.readAllLines(Paths.get(SOURCE_FILE))) {
if (isHeader) {
isHeader = false;
}
else {
String[] snippets = line.split(",");

entities.add(new Entity(
Integer.parseInt(snippets[ID]),
snippets[NAME],
Double.parseDouble(snippets[WEIGHT])
));
}
}
}
}

如何执行相同的操作但使用 Collector在实体集合中呈现数据,如下所示?

List<Entity> entities = Files.lines(Paths.get(SOURCE_FILE)).collect(...);

最佳答案

List<Entity> entities = 
Files.lines(Paths.get(SOURCE_FILE))
.skip(1) // skip the header line
.map(line -> line.split(",")) // transform each line to an array
.map(snippets -> new Entity(Integer.parseInt(snippets[ID]),
snippets[NAME],
Double.parseDouble(snippets[WEIGHT])) // transform each array to an entity
.collect(Collectors.toList());

代码注意事项:您应该使用 truefalse,而不是 Boolean.TRUEBoolean.FALSE (它们是 boolean 值的实例,而不是原始 boolean 值)。

关于Java 8 & NIO/读取行 -> 收集到实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24979611/

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