4

I have a Question about comparing two String Arrays in an efficient way. I want to know which String of stArr1 contains any String of stArr2. If yes I want to print the String in which I found it and the index of the String in the stArr1.

What I got so far is an easy way of comparing two strings:

public class Main {

    public static void main(String[] args) {

        String[] stArr1 = {"I am testing", "hi", "bye bye"};
        String[] stArr2 = {"hello", "bye", "test"};

        int matches = 0;

        for (int i = 0; i < stArr1.length; i++) {
            for (int j = 0; j < stArr2.length; j++) {
                if (stArr1[i].contains(stArr2[j])) {
                    System.out.println(stArr1[i] + "found at index " i);
                }
            }
        }
    }
}

So the output should be: I am testing found at index 0, bye bye found at index 2.

Does anybody know a more efficient way? I tried a little bit with streams and am pretty sure there is a better solution than that.

4
  • I am sorry, I was in a rush and I didn't take my time to truly review this question, forget about what I have said, you code is right and efficient, whilst being easy to read and understand. Commented Jan 7, 2020 at 0:28
  • does "an efficient way" mean fastest execution time? least use of memory? fewest lines of code? Commented Jan 7, 2020 at 0:31
  • @user85421 The OP implied by example that they wanted to find multiple matches so all strings should be checked. Commented Jan 7, 2020 at 1:26
  • 1
    There is a solution that would be potentially more efficient, but it has nothing to do with the Stream API. You have to decide what your question is about, a Stream API solution or a more efficient approach. Commented Jan 7, 2020 at 8:42

1 Answer 1

3

You can use IntStream combined with the anyMatch operator to get this thing done. Streams API is versatile such that any practical computation can be performed using streams. But, just because you can, doesn't mean you should. I still prefer the iterative approach and it is much more readable than the streams solution at least to me. So, my recommendation to you is to keep the iterative solution.

IntStream.range(0, stArr1.length)
    .filter(i -> Arrays.stream(stArr2).anyMatch(s -> stArr1[i].contains(s)))
    .forEach(i -> System.out.println(stArr1[i] + " found at index " + i));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.