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


当前回答

带有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()));

如果你使用Guava库:

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

或者,更好:

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

在Java 1.8中,流API可用于将列表转换为集合。例如,下面的代码显示了一个列表到一个集合的转换:

List<String> empList = Arrays.asList("java", "python", ".net", "javaScript", "php");
Set<String> set = empList.stream().collect(Collectors.toSet());
set.forEach(value -> System.out.printf("%s ", value));

如果列表包含对象,我想创建一个集合:

List<Employee> empList = Arrays.asList(new Employee(1, 1000, "Chandra Shekhar", 6000),
new Employee(2, 1000, "Rajesh", 8000), new Employee(3, 1004, "Rahul", 9000),
new Employee(4, 1001, "Suresh", 12000), new Employee(5, 1004, "Satosh", 7000));

Set<String> set = empList.stream().map(emp -> emp.getName()).collect(Collectors.toSet());
System.out.println(set);        

如果使用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 8来说非常简单:

List < UserEntity > vList= new ArrayList<>(); 
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());