11

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)

akash
  • 22,664
  • 11
  • 59
  • 87
richersoon
  • 4,682
  • 13
  • 44
  • 74

8 Answers8

11

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));
akash
  • 22,664
  • 11
  • 59
  • 87
8

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.

fps
  • 33,623
  • 8
  • 55
  • 110
4

It seems you are playing with array's, so I'm not going to use any Magic classes here. Just with pure arrays, you can do

public boolean checkArrayEquals() {
    String[] x = { "1", "2", "3" };
    String[] y = { "2", "5", "6" };
    for (int i = 0; i < x.length; i++) {
        String xval = x[i];
        for (int j = 0; j < y.length; j++) {
            if (xval.equals(y[j])) {
                return true;
            }
        }
    }
    return false;
 }
Manwal
  • 23,450
  • 12
  • 63
  • 93
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
4

There isn't a built in method but you can write your own utility method that will use a Set and look for matches.

private boolean sharesAnElement(String[] a, String[] b) {
    Set<String> bSet = new HashSet<>(Arrays.asList(b));

    for (String str : a) {
        if (bSet.contains(str)) {
            return true;
        }
    }

    return false;
}
frostmatthew
  • 3,260
  • 4
  • 40
  • 50
4

This is a rather specific need and I do not think that any of the popular collection libraries has a special function for that. You could do:

Collection<String> set = new HashSet<String>(Arrays.asList(x));
boolean result = false;
for (String str: y) {
    result |= set.contains(str);
}

Which has O(n) complexity rather than the O(n^2) of iterating through both arrays and compare element by element.

Markus
  • 309
  • 2
  • 11
2

You can use java.util.Set, e.g. HashSet for this:

  1. Insert all elements from x into the set
  2. Use Set#contains(Object) to check if the set contains any elements from y

http://docs.oracle.com/javase/8/docs/api/java/util/Set.html

http://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html

Cinnam
  • 1,892
  • 1
  • 15
  • 23
2

This might help. Change the printing statement to return true; if you want.

for (int i = 0; i < x.length; i++) {
    for (int j = 0; j < y.length; j++) {
        if (x[i].equals(y[j])) {
            System.out.println(x[i] + " is equal to " + y[j]);
        }
    }
}
hata
  • 11,633
  • 6
  • 46
  • 69
Raghaddee
  • 23
  • 3
2

Solution can be you can iterate array1 value and search in second array with each element.

public static void compareArrays(String[] array1, String[] array2) {
    boolean b = false;

    for(String str1 : array1){
        for(String str2 : array2){
            if(str1 == str1){
                b = true;
                break;
            }
        }
    }
    System.out.println(b);
}

Complete code:

public class HelloWorld{

     public static void main(String []args){
        String[] x = {"1","2","3"};
        String[] y = {"3","5","6"};
        compareArrays(x, y);
     }

     public static void compareArrays(String[] array1, String[] array2) {
        boolean b = false;

        for(String str1 : array1){
            for(String str2 : array2){
                if(str1 == str1){
                    b = true;
                    break;
                }
            }
        }
        System.out.println(b);
    }
}
Manwal
  • 23,450
  • 12
  • 63
  • 93