1

How can I return true if list1 and list2 share at least 1 item?

Example: list1 = (1,2,3) ... list2 = (2,3,4)

someFunction(list1, list2); // returns true

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

5 Answers5

8

Take a look at the Collections.disjoint method. If it is true there are no items in common.

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
  • +1 Looks like that method attempts to optimize by deciding which collection to iterate and which to check with `contains`, based on a few factors. [\[source\]](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Collections.java#Collections.disjoint%28java.util.Collection%2Cjava.util.Collection%29) – Paul Bellora Apr 16 '13 at 05:23
1

Like TofuBeer said, take a look at Collections.disjoint (I'd upvote his if I had any reputation...):

public void main() {
    List<Integer> list1 = Arrays.asList(1,2,3);
    List<Integer> list2 = Arrays.asList(2,3,4); 
    someFunction(list1, list2);
}

private boolean someFunction(List<Integer> list1, List<Integer> list2) {
    return ! Collections.disjoint(list1, list2);
}
jcreason
  • 857
  • 5
  • 15
0

Iterate over one list using "Iterator" and use contains method of other list to check the element. Isn't it?

Lokesh
  • 7,810
  • 6
  • 48
  • 78
0
public boolean someFunction(List<T> l1,List<T> l2)
{
    Iterator<T> i = l1.iterator();
    while(i.hasNext())
    {
        if(l2.contains(i.next())
            return true;
    }
    return false;
}
shiladitya
  • 2,290
  • 1
  • 23
  • 36
0

If space is not an issue, why not just use a HashMap?

Iterator it1 = list1.iterator(), it2 = list2.iterator();
Map <K, Integer> listmap = new HashMap <K, Integer> ();

while (it1.hasNext() && it2.hasNext()) {
    K elem1 = it1.next(), elem2 = it2.next();
    if ((listmap.get(elem1) != null && listmap.get(elem1) == 2) || 
        (listmap.get(elem2) != null && listmap.get(elem2) == 1)) {
        return false;
    }
    else {
        listmap.put(elem1, 1);
        listmap.put(elem2, 2);
    }

}
return true

This way, you don't have to loop through the entire second array to check each element of the first one, since adding elements to a hash table happens in amortized constant time.

By the way, a faster solution would be to use IntHashMap from Apache commons (or SparseArray on Android).

Keshav Saharia
  • 963
  • 7
  • 15