Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Lines Location occurrence, when filter is applied, stream, foreach

I don't know if is it possible:

I want to know the number line's where someWord is found in someFile.

   try {
      CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder()
          .onMalformedInput(CodingErrorAction.IGNORE);
      try (Reader r = Channels.newReader(FileChannel.open("path"), dec, -1);
          BufferedReader br = new BufferedReader(r)) {
        br.lines().filter(line -> line.contains("SomeWord"))
            .forEach(line -> System.out.println("location:" + line.????)); //Location where line has the "SomeWord"
      }
    } catch (IOException |java.io.UncheckedIOException ex) {
      Logger.getLogger(RecursiveFolderAndFiles.class.getName())
          .log(Level.SEVERE, null, ex);
    }

How I can to do this?


1 Answers

Instead of piping further operations on the br.lines() you can collect to a list then utilize IntStream.range like so:

...
...
List<String> resultSet = br.lines().collect(Collectors.toList());
IntStream.range(0, resultSet.size())
         .filter(index -> resultSet.get(index).contains("SomeWord"))
         .forEach(index -> System.out.println("location:" + index));
...
...

Now, you should have access to both the index and the lines.

like image 154
Ousmane D. Avatar answered Jun 09 '26 13:06

Ousmane D.



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!