Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

java - Split stream and put into list from text file

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;

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

and so on....

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("")).flatMap(Arrays::stream) 
                .collect(Collectors.toList());

    } catch (IOException e) {

        e.printStackTrace();
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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("")).map(factory::apply)  
             .collect(Collectors.toCollection(ArrayList::new));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...