Kevin Meredith
Kevin Meredith

Reputation: 41909

Comparing Java Lists

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

Upvotes: 1

Views: 296

Answers (5)

TofuBeer
TofuBeer

Reputation: 61526

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

Upvotes: 8

jcreason
jcreason

Reputation: 857

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);
}

Upvotes: 1

Keshav Saharia
Keshav Saharia

Reputation: 983

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).

Upvotes: 0

shiladitya
shiladitya

Reputation: 2310

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;
}

Upvotes: 0

Lokesh
Lokesh

Reputation: 7940

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

Upvotes: 0

Related Questions