#433 Reusing a Stream Inside a Loop

Companies:
Innotech
Themes:
JavaStreams & LambdasCode Review

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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in