Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Stream of Lines to extract comma seperated data

Each line in the file has comma seperated data.I need to extract each field based on comma from each row as String and store as property. How to achieve that using Java Streams?

Stream<String> lines = Files.lines(wiki_path);
like image 879
darshan kamat Avatar asked Oct 28 '25 07:10

darshan kamat


1 Answers

Read from the file:

Files::lines returns a sequence of lines Stream<String> which might be used for your advantage.

List<String> propertyList = Files.lines(wiki_path)    // Stream<String>      
        .map(line ->line.split(";"))                  // Stream<String[]>
        .flatMap(Arrays::stream)                      // Stream<String>
        .collect(Collectors.toList());                // List<String>

The result is a List of all the properties read from the file separated with a new line and the ; delimiter.


Write to Properties:

Since the properties are built on the key-value principle, you need the key for each loaded property. Let's suppose the value = key:

Properties properties = new Properties();
propertyList.forEach(property -> properties.set(property, property ));

This is rather a very primitive example and you have to amend it to your needs. Read more about properties at Properties.

like image 148
Nikolas Charalambidis Avatar answered Oct 31 '25 00:10

Nikolas Charalambidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!