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


当前回答

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

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

其他回答

可以将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 8你可以使用stream:

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

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

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

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

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

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