How to remove duplicates from a list in Java?

To remove duplicates from a list in Java, do this: list.stream().distinct().collect(Collectors.toList()).

Here's how you do it:

java.util.List<String> list = new java.util.ArrayList<>();

list.add("Hello");
list.add("World!");
list.add("World!");
list.add("World!");
list.add("World!");

java.util.List<String> listWithoutDuplicates = list
  .stream()
  .distinct()
  .collect(java.util.stream.Collectors.toList());

// [Hello, World!, World!, World!, World!]
System.out.println(list);

// [Hello, World!]
System.out.println(listWithoutDuplicates);