【问题标题】:Java stream split lines and store in different objectsJava流拆分行并存储在不同的对象中
【发布时间】:2018-10-29 07:01:23
【问题描述】:

我正在尝试理解 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 分隔。我想要做的是声明一个类,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<String> stream = Files.lines(Paths.get(file))) {  

            stream.map(line->line.split("\t"));


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

好吧,我必须以某种方式拆分每一行并将其存储在适合 MonitoredData 属性的对象中。我该怎么做?

【问题讨论】:

  • stream.map(line -&gt; line.split("\t")).map(v -&gt; new MonitoredData(sd.parse(v[o]), sd.parse(v[1]), v[2]).collect(toList());
  • @Boris the Spider ...sd.parse(v[o])... 应该是 ...sd.parse(v[0])... ;)
  • SimpleDateFormat sd。您编写代码...

标签: java split java-8 java-stream lines


【解决方案1】:

您只需添加另一个map 操作,如下所示:

 stream.map(line -> line.split("\t"))
       .map(a -> new MonitoredData(a[0], a[1], a[2]))
       .collect(Collectors.toList());

然后使用toList 收集器收集到一个列表。

【讨论】:

  • @BoristheSpider 不确定这是否是 OP 想要的,因为在 MonitoredData 类中 start_timeend_time 是字符串,而 SimpleDateFormat.parse 将产生一个 Date 实例。
  • 嗯 - 公平点 - 确实提出了为什么 SDF 开始存在的问题......(有一个 +1)
  • @BoristheSpider 谢谢! OP 提到“我稍后会尝试转换此 DateFormat 中的字符串”,所以我假设 SimpleDateFormat 实例用于他们想要执行的后续操作。
  • 使用"\t" 作为正则表达式没有错。 "\\t" 是一个引用 的特殊字符模式,而 "\t" 只匹配 字符。结果是一样的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多