Stream filter.findfirst
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't figure out how to use filter.findfirst
show my example
4 answers
From the question, it is not quite clear what you 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);
It will stop at the first found element when using filter
and findFirst
.
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 values that are suitable for the filter, I recommend writing this (in this case, only "12" will be output, since peek
is already after the filter.):
Optional<String> found = stringStream
.filter(s -> s.contains("12"))
.peek(System.out::println)
.findFirst();
You really need it .filter And then 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();
Expanded lambda
new Predicate<Integer>() {
@Override
public boolean test(Integer integer) {
return integer == 7;
}
}
I suspect that path
is responsible for the names of the files that are viewed, and if the file has the desired substring ("12"), then the name of this file (path
) is output. If the author wanted such logic, 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();
}
}