$show=/label

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

SHARE:

A quick guide to how to compare two HashSet objects in java for equality using equals(). Learn what is the fastest way to compare two sets in java 8 .

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.

Comparing Two Sets In Java 8


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,12,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,77,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How to compare two HashSet for equality in Java 8? (Fastest Way)
How to compare two HashSet for equality in Java 8? (Fastest Way)
A quick guide to how to compare two HashSet objects in java for equality using equals(). Learn what is the fastest way to compare two sets in java 8 .
https://1.bp.blogspot.com/-_qrAYRHmurY/XykSPWxKerI/AAAAAAAAC4E/3QHbeTXcE-EPrRt2DZf9yoe2o7haon9fwCLcBGAsYHQ/w640-h392/How%2Bto%2Bcompare%2Btwo%2BHashSet%2Bfor%2Bequality%2Bin%2BJava%2B8%253F%2B%2528Fastest%2BWay%2529.png
https://1.bp.blogspot.com/-_qrAYRHmurY/XykSPWxKerI/AAAAAAAAC4E/3QHbeTXcE-EPrRt2DZf9yoe2o7haon9fwCLcBGAsYHQ/s72-w640-c-h392/How%2Bto%2Bcompare%2Btwo%2BHashSet%2Bfor%2Bequality%2Bin%2BJava%2B8%253F%2B%2528Fastest%2BWay%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/how-to-compare-two-hashset-for-equality-in-java.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/how-to-compare-two-hashset-for-equality-in-java.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content