try { Stream<String> stringStream = Files.lines(path, StandardCharsets.UTF_8); stringStream.forEach((String e) -> { if (e.contains("12")) { System.out.println(path); break; // как остановить работу если нашёл нужное } }); } catch (IOException e) { e.printStackTrace(); } 

I can not understand how to use filter.findfirst show on my example

  • 3
    Describe in more detail what you want to achieve. While it is clear that you are trying to use the stream in the imperative style, which is fundamentally wrong. - Sergey Gornostaev

4 answers 4

From the question it is not quite clear what I want, but I will assume

 Stream<String> stringStream = Files.lines(path, StandardCharsets.UTF_8); Optional<String> firstStr = stringStream.filter(i -> i.contains("12")).findFirst(); firstStr.ifPresent(System.out::println); 

    He and so when using filter and findFirst will stop on the first element found. How to check? Like this:

     Stream<String> stringStream = Stream.of("345", "12", "789", "101112"); Optional<String> found = stringStream.filter(s -> { System.out.println(s); return s.contains("12"); }).findFirst(); 

    345

    12

    If you need to additionally output the appropriate values ​​for the filter, then I recommend writing as follows (in this case, only "12" is displayed, since peek after the filter is already worth it):

     Optional<String> found = stringStream .filter(s -> s.contains("12")) .peek(System.out::println) .findFirst(); 

      You really need .filter And then you check if something is in optional.

       Stream<Integer> stringStream = Arrays.stream(new Integer[]{5, 7, 15 , 7}); Optional<Integer> result = stringStream.filter(integer -> integer == 7).findFirst(); 

      Opened lambda

       new Predicate<Integer>() { @Override public boolean test(Integer integer) { return integer == 7; } } 

        I suspect that path is responsible for the names of files that are scanned, and if the file contains the required substring ("12"), then the name of this file ( path ) is displayed. If the author wanted this logic, then it is better to use .anyMatch (): For example, there are 3 files: 1.txt, 2.txt, 3.txt

          for (int i = 0; i < 3; i++) { Path path = new File((i + 1) + ".txt").toPath(); try { Stream<String> stringStream = Files.lines(path, StandardCharsets.UTF_8); if (stringStream.anyMatch(s -> s.contains("12"))) { System.out.println(path); } } catch (IOException e) { e.printStackTrace(); } }