How to remove duplicates from ArrayList in Java?

To remove duplicates from ArrayList in Java, first create a Set from your List, then clear the List, finally addAll from Set.

Here's how you do it:

var arrayList = new java.util.ArrayList<>();
arrayList.add("Hello");
arrayList.add("Hello");
arrayList.add("World");
arrayList.add("!");
System.out.println(arrayList); // [Hello, Hello, World, !]

var setFromArrayList = new java.util.HashSet<>(arrayList);
arrayList.clear();
arrayList.addAll(setFromArrayList);
System.out.println(arrayList); // [Hello, World, !]