Example 1: Remove duplicate elements from ArrayList using Set
Output
ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3] ArrayList without duplicate elements: [1, 2, 3, 4]
In the above example, we have created an arraylist named numbers. The arraylist contains duplicate elements.
To remove duplicate elements from the arraylist, we have
- add all elements from arraylist to set
- empty the arraylist using
clear()method - add all elements from set to arraylist
Here, we have used the LinkedHashSet to create a set. It is because it removes the duplicate elements and maintains insertion order. To learn more, visit Java LinkedHashSet.
Example 2: Remove duplicate elements from ArrayList using Stream
Output
ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3] ArrayList without duplicate elements: [1, 2, 3, 4]
In the above example, we have created an arraylist named numbers. The arraylist contains duplicate elements.
Here, we have used the Stream class to remove duplicate elements from the arraylist.
- numbers.stream() - create a stream from the arraylist
- stream.distinct() - removes duplicate elements
- stream.collect(Collectors.toList()) - returns a list from the stream
Here, we have used typecasting to convert the returned list into an arraylist.