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.
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With