We simply need to pass the list into the constructor of HashSet. It will remove all the duplicates from the list.
package com.jts;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SetFromListExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(101);
list.add(102);
list.add(103);
list.add(101);
list.add(104);
list.add(102);
System.out.println("List : " + list);
Set<Integer> set = new HashSet<>(list);
System.out.println("Set : " + set);
}
}
Output:
List : [101, 102, 103, 101, 104, 102]
Set : [101, 102, 103, 104]
If we want to maintain the same order of elements as list, then we should use LinkedHashSet class instead of HashSet.