在 Java 中将
List
转换为 Set
最简单的方法是什么?
Set<Foo> foo = new HashSet<Foo>(myList);
我同意 sepp2k,但还有一些其他细节可能很重要:
new HashSet<Foo>(myList);
会给你一个未排序的集合,其中没有重复项。在这种情况下,可以使用对象上的 .equals() 方法来识别重复。这是与 .hashCode() 方法结合完成的。 (有关平等的更多信息,请参阅此处)
给出排序集的另一种选择是:
new TreeSet<Foo>(myList);
如果 Foo 实现了 Comparable,这才有效。如果没有,那么您可能需要使用比较器:
Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);
这取决于compareTo()(来自可比较接口)或compare()(来自比较器)以确保唯一性。因此,如果您只关心唯一性,请使用 HashSet。如果您需要排序,请考虑 TreeSet。 (记住:稍后优化!)如果时间效率很重要,请使用 HashSet;如果空间效率很重要,请查看 TreeSet。请注意,可以通过 Trove(和其他位置)获得更有效的 Set 和 Map 实现。
Java- addAll
set.addAll(aList);
Java- 新对象
new HashSet<>(list)
Java-8
list.stream().collect(Collectors.toSet());
使用番石榴
Sets.newHashSet(list)
阿帕奇共享资源
CollectionUtils.addAll(targetSet, sourceList);
Java 10
var set = Set.copyOf(list);
如果您使用 Guava 库:
Set<Foo> set = Sets.newHashSet(list);
或者更好:
Set<Foo> set = ImmutableSet.copyOf(list);
使用java 8你可以使用流:
List<Integer> mylist = Arrays.asList(100, 101, 102);
Set<Integer> myset = mylist.stream().collect(Collectors.toSet()));
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);
}
}
}
请记住,从 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 Collections : 您还可以使用 Commons Collections 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);
使用流:另一种方法是将给定列表转换为流,然后流式传输以设置:-
// 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());
Set#copyOf
轻松将 List<E>
转换为不可修改的 Set<E>
:
示例:
var set = Set.copyOf(list);
请记住,这是一个无序操作,
null
元素是不允许的,因为它会抛出一个NullPointerException
。
如果您希望它是可修改的,那么只需将其传递给构造函数一个
Set
实现即可。
我会在转换为集合之前执行空检查。
if(myList != null){
Set<Foo> foo = new HashSet<Foo>(myList);
}
对于 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);
}
我们不要忘记我们相对较新的朋友,java-8流API。 如果您需要在将列表转换为集合之前对其进行预处理,最好有类似的东西:
list.stream().<here goes some preprocessing>.collect(Collectors.toSet());
使用构造函数的最佳方式
Set s= new HashSet(list);
在java 8中你还可以使用stream api::
Set s= list.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
)。
更具 Java 8 弹性的解决方案,具有
Optional.ofNullable
Set<Foo> mySet = Optional.ofNullable(myList).map(HashSet::new).orElse(null);
如果您使用Eclipse Collections:
MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();
MutableSet
接口扩展了 java.util.Set
,而 MutableIntSet
接口则不然。您还可以使用 Iterable
工厂类将任何 Set
转换为 Sets
。
Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));
Eclipse Collections 中提供了有关可变工厂的更多说明这里。
如果您想要从
ImmutableSet
获得 List
,您可以使用 Sets
工厂,如下所示:
ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))
注意:我是 Eclipse Collections 的提交者
在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);
最简单的方法*
集合 set = new HashSet(mylist);
System.out.println(set);