We can remove duplicates from a List in Java in the following ways:
- By converting the List into a Set
- Using Java 8 Streams
Remove duplicates from a List in Java by converting the List into a Set
A Set is a Collection that cannot contain duplicate elements. When we convert a List into a Set, all duplicates will be removed.
import java.util.*; public class Test { public static void main(String[] args) { List<String> names = new ArrayList<>(Arrays.asList("Megan", "Tom", "Steve", "Megan", "Meliisa", "Tom", "John")); Set<String> uniqueNames = new HashSet<>(names); // creating a Set from the List System.out.println(uniqueNames); } }
Output: [Megan, Tom, Steve, John, Meliisa]
Remove duplicates from a List in Java using the Java 8 Streams
Below is the program where we use distinct() method from the Streams API to remove duplicate elements from a list:
import java.util.*; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { List<String> names = new ArrayList<>(Arrays.asList("Megan", "Tom", "Steve", "Megan", "Meliisa", "Tom", "John")); List<String> uniqueNames = names.stream().distinct().collect(Collectors.toList()); System.out.println(uniqueNames); } }
Output: [Megan, Tom, Steve, Meliisa, John]
That’s it!