Java Online Compiler
Example: List Equality Using Sets in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// List Equality Using Sets import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create lists, including one with duplicates List<Integer> listA = new ArrayList<>(Arrays.asList(1, 2, 3, 2)); List<Integer> listB = new ArrayList<>(Arrays.asList(3, 1, 2)); List<Integer> listC = new ArrayList<>(Arrays.asList(1, 2, 4)); // Different element List<Integer> listD = new ArrayList<>(Arrays.asList(1, 2, 2, 3)); // Same elements, different duplicates System.out.println("Original listA: " + listA); System.out.println("Original listB: " + listB); System.out.println("Original listC: " + listC); System.out.println("Original listD: " + listD); // Step 2: Convert lists to sets Set<Integer> setA = new HashSet<>(listA); Set<Integer> setB = new HashSet<>(listB); Set<Integer> setC = new HashSet<>(listC); Set<Integer> setD = new HashSet<>(listD); System.out.println("\nSet from listA: " + setA); System.out.println("Set from listB: " + setB); System.out.println("Set from listC: " + setC); System.out.println("Set from listD: " + setD); // Step 3: Compare the sets using Set.equals() boolean areEqualAAndB = setA.equals(setB); boolean areEqualAAndC = setA.equals(setC); boolean areEqualAAndD = setA.equals(setD); // Note: this will be true if sets are used System.out.println("\nAre listA and listB equal (using sets)? " + areEqualAAndB); System.out.println("Are listA and listC equal (using sets)? " + areEqualAAndC); System.out.println("Are listA and listD equal (using sets)? " + areEqualAAndD); } }
Output
Clear
ADVERTISEMENTS