4

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.

Psycho_Coder
  • 235
  • 2
  • 9

2 Answers2

9

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]));
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • Addendum: Not 100% sure, but I think the stream will auto-close after the operation, so the try-with-resource is probably not necessary. – tobias_k Oct 21 '15 at 15:53
1

You do not want to call flatMap, as that will give you a single stream of entries, and you will not have the ability to process them properly. Instead, you want to

  1. filter the produced arrays on predicate data.equals(dictData[2])
  2. map the filtered arrays so that you get the first element
  3. for each element, print the appropriate message.
Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40