Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays for any similar value [duplicate]

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)

like image 825
richersoon Avatar asked Sep 12 '15 12:09

richersoon


2 Answers

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));
like image 89
akash Avatar answered Oct 06 '22 00:10

akash


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.

like image 27
fps Avatar answered Oct 06 '22 01:10

fps