#433 Reusing a Stream Inside a Loop
Analyze the code and answer whether the function is implemented correctly from the perspective of Java execution logic.
The code is valid and compiles.
import java.util.Arrays;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class Main {
private static String[] controlWords = new String[]{"person", "animal", "ferret"};
public static void main(String[] args) {
test("a person is an animal to another person");
test("a person is not a ferret but is not an animal either");
test("");
test(null);
}
private static void test(String line) {
String[] words = line.split(" ");
Stream wordsStream = Arrays.asList(words).stream();
for (int i = 0; i < controlWords.length; i++) {
if (wordsStream.anyMatch(Predicate.isEqual(controlWords[i]))) {
log("Found word: " + controlWords[i]);
}
}
log("Check completed");
}
private static void log(String msg) {
System.out.println(msg);
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor