简体   繁体   English

两个字符串数组的 Java 比较

[英]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.我想知道 stArr1 的哪个字符串包含 stArr2 的任何字符串。 If yes I want to print the String in which I found it and the index of the String in the stArr1.如果是,我想打印我在其中找到它的字符串以及 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.所以输出应该是:我正在测试在索引 0 处找到,在索引 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.您可以将IntStreamanyMatch运算符结合使用来完成此操作。 Streams API is versatile such that any practical computation can be performed using streams. Streams API 是通用的,因此可以使用流执行任何实际计算。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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