Java Program to compare two sets

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our 1st Set:

String arr[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set1 = new HashSet<String>(Arrays.asList(arr));

Let’s say the following is our 2nd Set:

arr = new String[] { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set2 = new HashSet<String>(Arrays.asList(arr));

Now let us compare the two sets. TRUE return value means both the sets are equals, whereas FALSE is returned:

set1.equals(set2)

Example

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] a) {
      String arr[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
      Set<String> set1 = new HashSet<String>(Arrays.asList(arr));
      arr = new String[] { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
      Set<String> set2 = new HashSet<String>(Arrays.asList(arr));
      System.out.println("Both the sets are equal? = "+set1.equals(set2));
   }
}

Output

Both the sets are equal? = true
raja
Published on 24-Apr-2019 16:13:48
Advertisements