将List转换为Set的最简单方法Java

在Java中将List转换为Set的最简单方法是什么?

660906 次浏览
Set<Foo> foo = new HashSet<Foo>(myList);

我同意sepp2k,但还有一些其他细节可能很重要:

new HashSet<Foo>(myList);

将为您提供一个没有重复项的未排序集合。在这种情况下,使用对象上的. equals()方法来识别重复项。这是与. hashCode()方法结合使用的。(有关相等性的更多信息,请查看这里

给出排序集的另一种选择是:

new TreeSet<Foo>(myList);

如果Foo实现了可比较,这将有效。如果没有,那么您可能需要使用比较器:

Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);

这取决于compareTo()(来自可比较的接口)或比较器(来自比较器)来确保唯一性。所以,如果你只是关心唯一性,请使用HashSet。如果你在排序之后,然后考虑TreeSet。(记住:稍后优化!)如果时间效率很重要,如果空间效率很重要,请使用HashSet,请查看TreeSet。请注意,可以通过Trove(和其他位置)获得更有效的Set和Map实现。

如果您使用番石榴库:

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

或者,更好:

Set<Foo> set = ImmutableSet.copyOf(list);
Set<E> alphaSet  = new HashSet<E>(<your List>);

或完整示例

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class ListToSet
{
public static void main(String[] args)
{
List<String> alphaList = new ArrayList<String>();
alphaList.add("A");
alphaList.add("B");
alphaList.add("C");
alphaList.add("A");
alphaList.add("B");
System.out.println("List values .....");
for (String alpha : alphaList)
{
System.out.println(alpha);
}
Set<String> alphaSet = new HashSet<String>(alphaList);
System.out.println("\nSet values .....");
for (String alpha : alphaSet)
{
System.out.println(alpha);
}
}
}

在转换为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()));

有多种方法可以获得Set作为:

    List<Integer> sourceList = new ArrayList();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
sourceList.add(4);


// Using Core Java
Set<Integer> set1 = new HashSet<>(sourceList);  //needs null-check if sourceList can be null.


// Java 8
Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));


//Guava
Set<Integer> set4 = Sets.newHashSet(sourceList);


// Apache commons
Set<Integer> set5 = new HashSet<>(4);
CollectionUtils.addAll(set5, sourceList);

当我们使用Collectors.toSet()时,它返回一个集合,根据文档:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned。如果我们想得到一个HashSet,那么我们可以使用另一种方法来得到一个集合(检查set3)。

对于Java8来说,这很容易:

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

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

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

具有Optional.ofNullable的更Java8弹性解决方案

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

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

示例:

var set = Set.copyOf(list);

请记住,这是一个无序操作,null元素是没有允许的,因为它会抛出NullPointerException

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

使用构造函数的最佳方法

Set s= new HashSet(list);

在Java 8中,您还可以使用流API::

Set s= list.stream().collect(Collectors.toSet());

Java-添加所有

set.addAll(aList);

Java-新对象

new HashSet<>(list)

Java-8

list.stream().collect(Collectors.toSet());

使用Guva

 Sets.newHashSet(list)

Apache Commons

CollectionUtils.addAll(targetSet, sourceList);

Java10

var set = Set.copyOf(list);

如果您使用Eclipse集合

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

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

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

在Eclipse集合这里中有更多关于可变工厂的解释。

如果您想从List获得ImmutableSet,您可以使用Sets工厂,如下所示:

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

注意:我是Eclipse集合的提交者

请记住,从List转换为Set将从集合中删除重复项,因为List支持重复项,但Set不支持Java中的重复项。

直接转换:将List转换为Set的最常见和最简单的方法

// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");


// Converting a list to set
Set<String> set = new HashSet<>(list);

Apache Commons集合:您还可以使用共享资源集合API将列表转换为集合:-

// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");


// Creating a set with the same number of members in the list
Set<String> set = new HashSet<>(4);


// Adds all of the elements in the list to the target set
CollectionUtils.addAll(set, list);

使用Stream:另一种方法是将给定列表转换为流,然后流设置:-

// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");


// Converting to set using stream
Set<String> set = list.stream().collect(Collectors.toSet());

在Java1.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);