简体   繁体   中英

Java comparison of two String Arrays

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM