拆分流并从文本文件中放入列表 [英] Split stream and put into list from text file

查看:131
本文介绍了拆分流并从文本文件中放入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将我从文本文件中读取的所有元素放入 ArrayList< MonitoredData> 使用 streams ,其中monitoredData类具有以下3个私有变量: private Date startingTime,Date finishTime,String activityLabel ;

How can I put all the elements I read from a text file into an ArrayList < MonitoredData > using streams, where monitoredData class has these 3 private variables: private Date startingTime, Date finishTime, String activityLabel;

File Activities.txt文本如下所示:

The text File Activities.txt looks like this:

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

依旧......

第一个2个字符串由一个空格分隔,然后是2个制表符,再一个空格,2个制表符。

The first 2 strings are separated by one blank space, then 2 tabs, one space again, 2 tabs.

String fileName = "D:/Tema 5/Activities.txt";

    try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

        list = (ArrayList<String>) stream
                .map(w -> w.split("\t\t")).flatMap(Arrays::stream)  //  \\s+
                .collect(Collectors.toList());

        //list.forEach(System.out::println);

    } catch (IOException e) {

        e.printStackTrace();
    }


推荐答案

你需要介绍一个工厂到创建 MonitoredData ,例如我使用函数来创建 MonitoredData from String []

you need introduce a factory to create the MonitoredData, in example I'm using a Function to create a MonitoredData from String[]:

Function<String[],MonitoredData> factory = data->{
   DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   try{
     return new MonitoredData(format.parse(data[0]),format.parse(data[1]),data[2]);
     //                       ^--startingTime       ^--finishingTime      ^--label
   }catch(ParseException ex){
     throw new IllegalArgumentException(ex);
   }
};

那么您的代码在流上操作应如下所示,而您不需要使用收集者#toCollection

THEN your code operate on a stream should be like below, and you don't need casting the result by using Collectors#toCollection:

list = stream.map(line -> line.split("\t\t")).map(factory::apply)  
             .collect(Collectors.toCollection(ArrayList::new));

这篇关于拆分流并从文本文件中放入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆