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


当前回答

如果使用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的提交者

其他回答

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

例子:

var set = Set.copyOf(list);

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

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

对于Java 8来说非常简单:

List < UserEntity > vList= new ArrayList<>(); 
vList= service(...);
Set<UserEntity> vSet= vList.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);
}

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

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

使用java 8你可以使用stream:

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