我正在尝试理解java 8的Streams.目前,我有一个这种格式的.txt文件:
2011-11-28 02:27:59 2011-11-28 10:18:11 Sleeping
2011-11-28 10:21:24 2011-11-28 10:23:36 Toileting
2011-11-28 10:25:44 2011-11-28 10:33:00 Showering
2011-11-28 10:34:23 2011-11-28 10:43:00 Breakfast
这3个“项目”总是由TAB分隔.我想要做的是使用属性(String类型)声明一个类MonitoredData
start_time end_time activity
我想要实现的是使用流从文件中读取数据并创建MonitoredData类型的对象列表.
在阅读了Java 8后,我设法编写了以下内容,但后来我走到了尽头
public class MonitoredData {
private String start_time;
private String end_time;
private String activity;
public MonitoredData(){}
public void readFile(){
String file = "Activities.txt"; //get file name
//i will try to convert the string in this DateFormat later on
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//Store the lines from the file in Object of type Stream
try (Stream stream = Files.lines(Paths.get(file))) {
stream.map(line->line.split("\t"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
好吧,不知怎的,我必须拆分每一行并将其存储在一个适合MonitoredData属性的Object中.我怎么做?
解决方法:
您所要做的就是添加另一个地图操作,如下所示:
stream.map(line -> line.split("\t"))
.map(a -> new MonitoredData(a[0], a[1], a[2]))
.collect(Collectors.toList());
然后使用toList收集器收集到列表.
标签:lines,java,java-8,java-stream,split
来源: https://codeday.me/bug/20190828/1747373.html