To remove duplicates in a list in Java, you can use a Set to automatically eliminate duplicates.
In this example,
numbers
with integer values.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
Set<Integer> uniqueNumbers = new HashSet<>(numbers);
List<Integer> distinctNumbers = new ArrayList<>(uniqueNumbers);
System.out.println("List without duplicates: " + distinctNumbers);
}
}
List without duplicates: [1, 2, 3, 4, 5]
In this example,
words
with string values.import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "apple", "banana");
Set<String> uniqueWords = new HashSet<>(words);
List<String> distinctWords = new ArrayList<>(uniqueWords);
System.out.println("List without duplicates: " + distinctWords);
}
}
List without duplicates: [apple, banana, cherry]
In this tutorial, we learned How to Remove Duplicates in a List in Java language with well detailed examples.