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


当前回答

使用java 8你可以使用stream:

List<Integer> mylist = Arrays.asList(100, 101, 102);
Set<Integer> myset = mylist.stream().collect(Collectors.toSet()));

其他回答

使用构造函数的最好方法

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

如果你使用Guava库:

Set<Foo> set = Sets.newHashSet(list);

或者,更好:

Set<Foo> set = ImmutableSet.copyOf(list);

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

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