Noksuu
Noksuu

Reputation: 11

Comparing 2 HashSets for common object

I have one question, I have two HashSets,

Set<String> list1 = new HashSet<String>(oldList1);
Set<String> list2 = new HashSet<String>(oldList2);

And I would like to check if a "String" in list1 is present in list2. What would be the fastest way to go trough this? Keeping in mind that both sets have over 10k Strings, so something relatively fast would be nice.

Any help is appreciated!

Upvotes: 0

Views: 1175

Answers (2)

A Kunin
A Kunin

Reputation: 44472

Another option is to use Set restriction to add duplicate. Method add() will help you find all identical strings.

Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.

    Set<String> list1 = new HashSet<String>();
    list1.add("a");
    list1.add("b");
    list1.add("c");
    Set<String> list2 = new HashSet<String>();
    list2.add("b");
    list2.add("c");
    list2.add("d");
    Set<String> listCommon = new HashSet<String>();
    for (String element : list2) {
        if (!list1.add(element)) {
            listCommon.add(element);
        }
    }
    // all collected duplicates
    for (String element : listCommon) {
        System.out.println(element);
    }

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198571

If you want to check whether there is any string in list1 that is also in list2, you can just write

!Collections.disjoint(list1, list2)

which is true if they have any elements in common. If you want to find the answer, just do the straightforward loop:

for (String str : list1) {
  if (list2.contains(str)) {
    return str;
  }
}

Upvotes: 2

Related Questions