How to Compare Two Sets in Java


In this example, we will learn how to compare two sets in Java.

Source Code

package com.beginner.examples;

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

public class CompareTwoSets {

	public static void main(String[] args) {
		Set test1 = new HashSet();
        test1.add("a");
        test1.add("b");
        
        Set test2 = new HashSet();
        test2.add("b");
        test2.add("c");
        
        System.out.println(setEquals(test1,test2));
        
        Set test3 = new HashSet();
        test1.add("a");
        test1.add("b");
        
        Set test4 = new HashSet();
        test2.add("a");
        test2.add("b");
        System.out.println(setEquals(test3,test4));
	}
	
	public static boolean setEquals(Set set1, Set set2){

		if(set1 == null || set2 ==null){
			return false;
		}

		if(set1.size()!=set2.size()){
			return false;
		}

		return set1.containsAll(set2);

    }

}

Output:

false
true

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments