在Java中将列表转换为集的最简单的方法是什么?


当前回答

使用构造函数的最好方法

Set s= new HashSet(list);

在java 8中,你也可以使用stream api::

Set s= list.stream().collect(Collectors.toSet());

其他回答

可以将List<>转换为Set<>

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);
}

我将在转换为set之前执行Null检查。

if(myList != null){
Set<Foo> foo = new HashSet<Foo>(myList);
}

请记住,从List转换到Set将从集合中删除重复项,因为List支持重复项,而Set在Java中不支持重复项。

直接转换:将List转换为Set的最常见和最简单的方法

// 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 Collections:你也可以使用Commons Collections API将一个List转换为一个Set

// 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);

使用流:另一种方法是将给定的列表转换为流,然后将流转换为集:-

// 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()); 

不要忘记我们相对较新的朋友,java-8流API。 如果你需要在将列表转换为集合之前对其进行预处理,最好是这样:

list.stream().<here goes some preprocessing>.collect(Collectors.toSet());

带有Optional.ofNullable的更具Java 8弹性的解决方案

Set<Foo> mySet = Optional.ofNullable(myList).map(HashSet::new).orElse(null);