Convert List to Set in Java
Description
The following code shows how to convert List to Set.
Example
//from w ww. j av a2 s . c o m
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
static <T> Set<T> listToSet(List<T> list) {
Set<T> set = new HashSet<T>();
set.addAll(list);
return set;
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("a");
list.add("e");
list.add("d");
list.add("f");
list.add("g");
list.add("a");
Set<?> set = listToSet(list);
System.out.println(set);
}
}
The code above generates the following result.