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


当前回答

Set<Foo> foo = new HashSet<Foo>(myList);

其他回答

如果使用Eclipse Collections:

MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();

MutableIntSet接口扩展了java.util.Set,而MutableIntSet接口没有。您还可以使用Sets工厂类将任何Iterable转换为Set。

Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));

在Eclipse Collections中有更多关于可变工厂的解释。

如果你想从List中获得一个ImmutableSet,你可以像下面这样使用Sets工厂:

ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))

注意:我是Eclipse Collections的提交者

使用构造函数的最好方法

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

在Java 10中,您现在可以使用Set#copyOf轻松地将List<E>转换为不可修改的Set<E>:

例子:

var set = Set.copyOf(list);

请记住,这是一个无序操作,不允许使用空元素,因为它将抛出NullPointerException异常。

如果您希望它是可修改的,那么只需将它传递给构造函数一个Set实现。

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

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