Split stream and put into list from text file

How can I put all the items I have read from a text file into ArrayList < MonitoredData >

using streams where the monitoringedData class has these 3 private variables private Date startingTime, Date finishTime, String activityLabel

:;

The Activities.txt text file 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

      

etc....

The first two lines are separated by one space, then by two tabs, one space, two 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();
    }

      

+3


source to share


1 answer


you need to inject a factory to create MonitoredData

, in the example i am using Function

to create 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);
   }
};

      



THEN your code is flowing, should look like below and you don't need to do the result with Collectors #toCollection :

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

      

+3


source







All Articles