3

How can I compare two hash sets in java ? My first hash sets looks like below.

static Set<String> nounPhrases = new HashSet<>();

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

static Set<String> nounPhrases2 = new HashSet<>();

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

user8048032
  • 145
  • 1
  • 1
  • 8
  • 1
    What results do you want? – Sweeper Jun 04 '17 at 15:37
  • 4
    Define "compare". Are you looking for intersection? Or both sets to have exactly the same elements? Also, what have you tried so far? – Jonathan Sudiaman Jun 04 '17 at 15:38
  • 1
    What's wrong with `seta.equals( setb )`? – laune Jun 04 '17 at 15:40
  • I need to check if there are similar nouns in both sets. And if they have similar nouns.. do another task – user8048032 Jun 04 '17 at 15:40
  • 3
    Now define "similar". And read the api documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#retainAll-java.util.Collection- – JB Nizet Jun 04 '17 at 15:41
  • I need to check if there are similar nouns in both sets. And if they have similar nouns.. do another task – user8048032 Jun 04 '17 at 15:43
  • 3
    Yes, yes, yes - but what is "similar" if it isn't "equals"? Or equalsIgnoreCase? Or something weird like "bee" similar to "bug"? – laune Jun 04 '17 at 15:45
  • sorry for my bad English. :( I need to check for equal words. – user8048032 Jun 04 '17 at 15:47
  • Welcome to Stack Overflow! Please take the [tour](http://stackoverflow.com/tour), have a look around, and read through the [help center](http://stackoverflow.com/help), in particular [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) and [What topics can I ask about here?](http://stackoverflow.com/help/on-topic). From that second link: "Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it." – Timothy Truckle Jun 04 '17 at 15:47
  • like both sets have noun "Java" then I show a message like system.out.println("They have java"); – user8048032 Jun 04 '17 at 15:50
  • Possible duplicate of [Common elements in two lists](https://stackoverflow.com/questions/5943330/common-elements-in-two-lists) – Tom Jun 04 '17 at 16:33

4 Answers4

6

This is a wheel already invented.

Set#equals() compares sets in the way you would expect:

set1.equals(set2)

If you want two Set variables that are both null to be "equal", then use:

Objects.equals(set1, set2)
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    @NextDeveloper no, it doesn’t compare order. `Object.equals()` invokes the equals method of the instance passed to it, and Set’s implementation of equals() doesn’t consider order, largely because Set doesn’t support order - it’s actually impossible for it to consider order. – Bohemian Oct 05 '19 at 23:37
0

So you mean like this?

public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    // Checking for every element in first set
    for (final String element : nounPhrases) {

        // if second set has the current element
        if (nounPhrases2.contains(element)) {
            System.out.println("They have " + element);
        }
    }
}

My output:

They have java
They have book

Edit: Based on your comment, if i understand correctly, if you want to get the common elements in both sets, just store the values and return them:

public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    System.out.println(getCommon(nounPhrases, nounPhrases2));
}

public final static Set<String> getCommon(Set<String> setA, Set<String> setB) {

    final Set<String> result = new HashSet<>();
    for (final String element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}

You could use generics to make the method work for other elements than strings:

public final static <T> Set<T> getCommon(Set<T> setA, Set<T> setB) {

    final Set<T> result = new HashSet<>();
    for (final T element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}

If performance is important, you should check sizes first and only iterate over the elements of the smaller set. If you have one set with 1 elements, and one set with 100, starting with the smaller will leve you with one iteration whereas starting with the bigger will leave you with 100 checks where only 1 could have been in both sets.

Dennux
  • 240
  • 1
  • 8
  • Hello I get below output. How can I show all the equal elements ?List of Noun Parse : [java, jsp, book] List of Noun Parse : [Java, developmet, web, JSP, book] They have - book – user8048032 Jun 04 '17 at 17:52
  • I don't understand your question. What output do you get? With my code, both book and java are printed out. – Dennux Jun 04 '17 at 17:55
  • when I run my code...I get output as this http://i.imgur.com/9FAInxu.png – user8048032 Jun 04 '17 at 18:37
  • Hello sir I found the problem. Because one of my set's elements are in uppercase letters and other one is in mixed cases.. so it shows only the words with matching cases.. ex - in both arrays "book" is similar. – user8048032 Jun 04 '17 at 18:46
  • Is it necessary for you that "book" and "Book" match? If so, just convert all strings to uppercase (or lowercase) in temporary sets first. – Dennux Jun 04 '17 at 18:51
0

If u want to find the common element then use collect(Collectors.toList()) instead of count , If u want simply to find how many set has common element using java 8

long count = nounPhrases.stream().filter(tempstring -> {
            return nounPhrases2.stream().anyMatch(tempstring2 -> {
                return tempstring.equals(tempstring2);
            });
        }).count();
        if (count > 0)
            System.out.println("has common elements-"+count);
        else
            System.out.println("not common");
  • Instead of filtering and use count(), you could just use anyMatch(). It would stop at the first match, and would thus be faster (and clearer). – JB Nizet Jun 04 '17 at 16:27
  • You left the count() there. anyMatch() returns a boolean. – JB Nizet Jun 04 '17 at 16:51
0

By the use of Java apache.commons.collections package we can implement

package com.StackoverFlow;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
public class MainClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        Set hs_1 = new HashSet();
        hs_1.add("A");
        hs_1.add("B");
        hs_1.add("C");
        hs_1.add("D");

        Set hs_2 = new HashSet();
        hs_2.add("A");
        hs_2.add("B");
        hs_2.add("C");
        hs_2.add("D");

        Collection result = CollectionUtils.subtract(hs_1, hs_2);
        System.out.println(result);
        if(result.isEmpty()){
            System.out.println("perform Task-->>Value maches  ");

        }else{
            System.out.println("perform Task-->>Value not maches  ");
        }

    }

}
Mayur Ingle
  • 85
  • 2
  • 7