I would like to compare two arrays, if at least one value can be found on both arrays.
Scenario #1 : 2
is found in both arrays, so the result is true
.
String[] x = {"1","2","3"};
String[] y = {"2","5","6"};
Scenario #2 : No matching value, so the result is false
.
String[] x = {"1","2","3"};
String[] y = {"4","5","6"};
Is there any built-in method in Java, or any library that can handle this requirement?
I would like to emphasize that I am looking for a Java library or any Java method that can do this out of the box.
The Collection.contains
is not an option because all values in both arrays should be the same in order to return true. (I need to return true if at least one value is similar in both arrays)
You can use Collections#disjoint
for that,
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));
In Java 8, you could use this:
String[] x = { "1", "2", "3" };
String[] y = { "2", "5", "6" };
Set<String> set = new HashSet<>(Arrays.asList(y));
boolean result = Arrays.stream(x).anyMatch(set::contains); // true
which is O(n)
.
This is the java 8 version of @Markus' answer, though anyMatch()
stops the iteration when a match is found.
NOTE: If x
and y
lengths are different, consider creating the stream around the array with less elements. This is because HashSet.contains()
method runs in O(1)
amortized time, irrespective of the length of set
, so for the worst case, iterating less times has better performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With