Compare Two Set in Java

In this example, We will show you sample program about, How to compare two set in Java. The example has been tested and shared in the same post.

Example Program

package com.dineshkrish;
import java.util.Set;
/**
* 
* @author Dinesh Krishnan
*
*/
public class SetCompareUtil {
public static boolean compare(Set<?> set1, Set<?> set2) {
if(set1 == null || set2 == null)
return false;
if(set1.size() != set1.size()) 
return false;
if(set1.containsAll(set2)) 
return true;
return false;
}
}

The SetCompareUtil.compare() method tested in the below class

package com.dineshkrish;
import java.util.Set;
import java.util.TreeSet;
/**
* 
* @author Dinesh Krishnan
*
*/
public class CompareSet {
public static void main(String[] args) {
// set object 1
Set<String> set1 = new TreeSet<String>();
set1.add("One");
set1.add("Two");
set1.add("Three");
set1.add("Four");
set1.add("Five");
// set object 2
Set<String> set2 = new TreeSet<String>();
set2.add("One");
set2.add("Two");
set2.add("Three");
set2.add("Four");
set2.add("Five");
if(SetCompareUtil.compare(set1, set2))
System.out.println("Equal");
else 
System.out.println("Not Equal");
}
}

Output

Equal

References

1. JavaDoc – Set Interface
2. JavaDoc – TreeSet Class

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *