The Set is also an interface in the ‘Java Collection‘ framework. Unlike a List, a Set does not allow duplicates. Hence you can use a Set to eliminate the duplicates in a List. There are several ways in which you can use a Set to eliminate duplicates as demonstrated below:
The most commonly used implementation of Set is HashSet. HashSet has a constructor which accepts a Collection as a parameter. So basically, if you create a new HashSet using this constructor and pass in the List as input, this will eliminate the duplicates. The following code demonstrates this:
Here, a new HashSet is created by passing the List as input. So this will automatically create a Set with the elements in the List and eliminate the duplicates. So this code prints the same output as before:
35 20 5 40 25 10 15
The problem with HashSet is that it does not maintain the order of elements. So you can see that the order of elements in the output is different from that in the input list.