Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split lines and process them by reading file using Java 8 Streams

Tags:

java

java-8

I have a huge file in the following format:-

First Line
Second Line
Third Line
Fourth Line
Fifth Line
Data1;Data2;Data3
Data1;Data2;Data3
Data1;Data2;Data3
....
....

I want my code to skip the first 5 lines and then for the rest of the lines it will split the line by ';' and do some string comparison with the third item. I wish to use Java 8 Streams for the purpose but unable to figure out how to work it out properly. I have done what I wish to do using BufferedReader and code is as follows:-

try (BufferedReader reader = Files.newBufferedReader(dictionaryPath)) {
            String line;
            reader.readLine();
            reader.readLine();
            reader.readLine();
            reader.readLine();
            reader.readLine();
            while ((line = reader.readLine()) != null) {
                String[] dictData = line.split(";");
                if (data.equals(dictData[2])) {
                    System.out.println("Your Data Item is: " + dictData[0]);
                    break;
                }
            }
        }

But I am not sure how I can achieve the same as above using Java 8 streams. I was trying something like the following:

try (Stream<String> lines = Files.lines(dictionaryPath)) {
         lines.skip(5).map(line -> line.split(";")).flatMap(Arrays::stream)

But couldn't understand more. I wish to get some assistance.

like image 513
Psycho_Coder Avatar asked Dec 24 '22 13:12

Psycho_Coder


1 Answers

You can try something like this:

Files.lines(dictionaryPath)
        .skip(5) // skip first five lines
        .map(line -> line.split(";")) // split by ';'
        .filter(dictData -> data.equals(dictData[2])) // filter by second element
        .findFirst() // get first that matches and, if present, print it
        .ifPresent(dictData -> System.out.println("Your Data Item is: " + dictData[0]));
like image 75
tobias_k Avatar answered Dec 28 '22 06:12

tobias_k