Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, December 28, 2021

How to compare two HashSet for equality in Java 8? (Fastest Way)

1. Overview


In this article, You'll learn how to compare two Sets in Java using Stream API.

Java HashSet class equals() method takes Object but when you are calling on a set object then you must pass the HashSet or Set implementation object.

Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

Let us see the examples using equals(), containsAll() method of the Set interface. In the end, We'll explore how to compare two HashSet in java 8.

How to compare two HashSet for equality in Java 8? (Fastest Way)



2. Example 1: How To Compare Two Set Values In Java


package com.javaprogramto.java8.compare.set;

import java.util.HashSet;
import java.util.Set;

public class CompareTwoSetExample {

    public static void main(String[] args) {

        Set<String> set1 = new HashSet<>();

        set1.add("Hello");
        set1.add("Java Developer");
        set1.add("Welcome");
        set1.add("To");
        set1.add("JavaProgramTo.com");


        Set<String> set2 = new HashSet<>();

        set2.add("Hello");
        set2.add("Java Developer");
        set2.add("Welcome");
        set2.add("To");
        set2.add("JavaProgramTo.com");

        boolean isEquals = set1.equals(set2);

        System.out.println("Is set 1 and set 2 equal ? : "+isEquals);

    }
}
Output:
Is set 1 and set 2 equal ? : true

In the above program, created two sets of objects and added the same values to it. After that invoked equals() method on set1 with argument set2.

As we know that values in both sets are the same so it returned true.

3. Example 2: HashSet equals() method for objects comparison


package com.javaprogramto.java8.compare.set;

import java.util.HashSet;
import java.util.Set;

public class SetEqualsMethodExample {

    public static void main(String[] args) {

        Set<Integer> set1 = new HashSet<>();

        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);
        set1.add(5);

        System.out.println("Set 2 values : "+set1);

        Set<Integer> set2 = new HashSet<>();

        set2.add(1);
        set2.add(2);
        set2.add(3);
        set2.add(4);
        set2.add(5);

        System.out.println("Set 2 values : "+set2);

        boolean isEquals = set1.equals(set2);

        System.out.println("Are both sets equal ? : "+isEquals);

    }
}

Output:
Set 2 values : [1, 2, 3, 4, 5]
Set 2 values : [1, 2, 3, 4, 5]
Are both sets equal ? : true

4. Fastest Way To Compare Two Sets In Java?


As of now, you have seen how to compare the two sets but if both sets are having huge data sets then you must have to think about What is the fastest way to compare two sets?

Set api has several methods do this but you have to choose the right one based on your use case.

Let us write examples with equals(), containsAll() and replaceAll() methods.

package com.javaprogramto.java8.compare.set;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetCompareFastestExample {

    public static void main(String[] args) {

        Set<Integer> set1 = new HashSet<>();

        set1.add(1);
        set1.add(20);
        set1.add(35);
        set1.add(14);
        set1.add(05);

        System.out.println("Set 2 values : " + set1);

        Set<Integer> set2 = new HashSet<>();

        set2.add(1);
        set2.add(05);
        set2.add(14);
        set2.add(20);
        set2.add(35);

        System.out.println("Set 2 values : " + set2);

        // Method 1: Using equals() method
        boolean isEquals = set1.equals(set2);
        System.out.println("Comparing in different ways ");
        System.out.println("Way 1 with equals :: " + isEquals);

        // Method 2: Using containsALl()
        boolean havingAll = set1.containsAll(set2);
        System.out.println("Way 2 with containsAll :: " + havingAll);

        // Method 3: Using removeAll()
        boolean removedAll = set1.removeAll(set2);
        System.out.println("Way 3 with removeAll :: " + removedAll);

        // Method 4: Using TreeSet
        TreeSet<Integer> treeSet1 = new TreeSet<>();
        treeSet1.add(1);
        treeSet1.add(20);
        treeSet1.add(35);
        treeSet1.add(14);
        treeSet1.add(05);

        TreeSet<Integer> treeSet2 = new TreeSet<>(set2);

        System.out.println("TreeSet 1 values are : "+treeSet1);
        System.out.println("TreeSet 2 values are : "+treeSet2);
        boolean isEqualsWithTreeSet = treeSet1.equals(treeSet2);
        System.out.println("Way 4: Equals comparison with tree map : "+isEqualsWithTreeSet);
} }

Output:
Set 2 values : [1, 35, 20, 5, 14]
Set 2 values : [1, 35, 20, 5, 14]
Comparing in different ways 
Way 1 with equals :: true
Way 2 with containsAll :: true
Way 3 with removeAll :: true
TreeSet 1 values are : [1, 5, 14, 20, 35]
TreeSet 2 values are : [1, 5, 14, 20, 35]
Way 4: Equals comparison with tree map : true
If any new value is added to any one of these two maps then it will return false in all the cases.
set2.add(45);
Now the values of set2 and TreeSet2 values are added with number 45. We could see the differences in both sets values. So, It should return false. 

Let us run the program and see the output now. 
Set 2 values : [1, 35, 20, 5, 14]
Set 2 values : [1, 35, 20, 5, 45, 14]
Comparing in different ways 
Way 1 with equals :: false
Way 2 with containsAll :: false
Way 3 with removeAll :: true
TreeSet 1 values are : [1, 5, 14, 20, 35]
TreeSet 2 values are : [1, 5, 14, 20, 35, 45]
Way 4: Equals comparison with tree map : false

So, the Final solution is to compare collections in a faster way is by sorting both collections first then call equals() method. But, Java TreeSet api does the fastest sorting internally so it is good to add the objects to the sorted set or map. 

Typically, Looks for the value in the Set in O(1) time whereas O(log(n)) in sorted TreeSet. So, Only for the larger data objects, you should consider the TreeSet over the HashSet.

5. Compare Two Sets in Java 8 Using Stream API (Any Collection Objects)


Stream API is added with many utility methods such as filter(), anyMatch(), findFirst() for comparisions.

Based on your use case, you can pick the right operations.
package com.javaprogramto.java8.compare.set;

import java.util.HashSet;
import java.util.Set;

public class CompareTwoSetsInJava8 {

    public static void main(String[] args) {

        Set<Integer> sectionAMarks = new HashSet<>();

        sectionAMarks.add(100);
        sectionAMarks.add(99);
        sectionAMarks.add(98);
        sectionAMarks.add(97);
        sectionAMarks.add(96);

        System.out.println("Section A marks : " + sectionAMarks);

        Set<Integer> sectionBMarks = new HashSet<>();

        sectionBMarks.add(96);
        sectionBMarks.add(97);
        sectionBMarks.add(98);
        sectionBMarks.add(99);
        sectionBMarks.add(100);

        System.out.println("Section B marks : " + sectionBMarks);

        boolean anySectionAMarksMatchesWithSecBMarks = sectionAMarks.stream().anyMatch(marks -> sectionBMarks.contains(marks));

        boolean noSectionAMarksMatchesWithSecBMarks = sectionAMarks.stream().noneMatch(marks -> sectionBMarks.contains(marks));

        boolean allSectionAMarksMatchesWithSecBMarks = sectionAMarks.stream().allMatch(marks -> sectionBMarks.contains(marks));

        System.out.println("Comparing the section A marks matches with the following cases");

        System.out.println("If any one marks matches with the section b marks: " + anySectionAMarksMatchesWithSecBMarks);

        System.out.println("If no marks matches with the section b marks: " + noSectionAMarksMatchesWithSecBMarks);

        System.out.println("If all matches with the section b marks: " + allSectionAMarksMatchesWithSecBMarks);

    }
}
Output:
Section A marks : [96, 97, 98, 99, 100]
Section B marks : [96, 97, 98, 99, 100]
Comparing the section A marks matches with the following cases
If any one marks matches with the section b marks: true
If no marks matches with the section b marks: false
If all matches with the section b marks: true

So, if you have custom objects in the set or collection then equals() and hashcode() methods should be overridden in the custom class. Because contains() method internally uses these two methods for object equality.

6. Conclusion


In this article, You've seen how to compare two sets of objects using normal java API and using Streams API.

All the examples are shown are over GitHub.


No comments:

Post a Comment

Please do not add any spam links in the comments section.