java – 比较两个数组的任何相似的值

前端之家收集整理的这篇文章主要介绍了java – 比较两个数组的任何相似的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Most efficient way to return common elements from two string arrays6
我想比较两个数组,如果两个数组中至少有一个值.

在这两个数组中找到方案#1:2,结果是正确的.

String[] x = {"1","2","3"};
String[] y = {"2","5","6"};

情况#2:没有匹配的值,所以结果为false.

String[] x = {"1","3"};
String[] y = {"4","6"};

Java中有任何内置方法,还是可以处理此要求的任何库?

我想强调,我正在寻找一个Java库或任何可以开箱即用的Java方法.

Collection.contains不是一个选项,因为两个数组中的所有值应该相同,以返回true. (如果两个数组中至少有一个值相似,则需要返回true)

解决方法

你可以使用 Collections#disjoint,

Returns true if the two specified collections have no elements in
common.

Note that it is permissible to pass the same collection in both parameters,in which case the method will return true if and only if the collection is empty.

boolean isNoCommonElements = Collections.disjoint(
                                        Arrays.asList(x),Arrays.asList(y));
原文链接:https://www.f2er.com/java/125329.html

猜你在找的Java相关文章