Set<T> set=new HashSet<T>();
//Added dependency -> If list is null then it will throw NullPointerExcetion.
Set<T> set;
if(list != null){
set = new HashSet<T>(list);
}
List<Integer> sourceList = new ArrayList();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
sourceList.add(4);
// Using Core Java
Set<Integer> set1 = new HashSet<>(sourceList); //needs null-check if sourceList can be null.
// Java 8
Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));
//Guava
Set<Integer> set4 = Sets.newHashSet(sourceList);
// Apache commons
Set<Integer> set5 = new HashSet<>(4);
CollectionUtils.addAll(set5, sourceList);
当我们使用Collectors.toSet()时,它返回一个集合,根据文档:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned。如果我们想得到一个HashSet,那么我们可以使用另一种方法来得到一个集合(检查set3)。
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting a list to set
Set<String> set = new HashSet<>(list);
Apache Commons集合:您还可以使用共享资源集合API将列表转换为集合:-
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Creating a set with the same number of members in the list
Set<String> set = new HashSet<>(4);
// Adds all of the elements in the list to the target set
CollectionUtils.addAll(set, list);
使用Stream:另一种方法是将给定列表转换为流,然后流设置:-
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting to set using stream
Set<String> set = list.stream().collect(Collectors.toSet());