This Java program demonstrates how to remove duplicates from an ArrayList using a Set. Here's how the code works:
Note that the LinkedHashSet class is used instead of the HashSet class to preserve the order of the elements in the original ArrayList. If the order of the elements is not important, the HashSet class can be used instead.
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class Remove_Duplicates { public static void main(String args[]) { List<Integer> num = new ArrayList<Integer>(); num.add(23); num.add(3); num.add(65); num.add(17); num.add(7); num.add(23); num.add(3); num.add(11); System.out.println("list of prime numbers : " + num); Set<Integer> primesWithoutDuplicates = new LinkedHashSet<Integer>(num); num.clear(); num.addAll(primesWithoutDuplicates); System.out.println("List of Numbers Without Duplicates : " + num); } }
list of prime numbers : [23, 3, 65, 17, 7, 23, 3, 11] List of Numbers Without Duplicates : [23, 3, 65, 17, 7, 11]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions