Rares Macavei
Rares Macavei

Reputation: 55

Java stream split lines and store in different objects

I'm trying to understand java 8's Streams. Currently, I have a .txt file with this format:

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   

Those 3 "items" are always separated by a TAB. What i want to do is to declare a class, MonitoredData, with attributes(of type String)

start_time  end_time  activity

What i want to achieve is to read the data from the file using streams and create a list of objects of type MonitoredData.

After reading about Java 8 i managed to write the following but then I reached a dead end

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

Well, somehow I have to split the each line and store it in a Object appropriate to MonitoredData's attribute. How do i do that?

Upvotes: 3

Views: 4944

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

All you have to do is add another map operation as shown below:

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

then collect to a list with the toList collector.

Upvotes: 6

Related Questions