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


当前回答

对于Java 8来说非常简单:

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

其他回答

Java——addAll

set.addAll(aList);

Java-新对象

new HashSet<>(list)

java 8

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

使用Guva

 Sets.newHashSet(list)

Apache Commons

CollectionUtils.addAll(targetSet, sourceList);

Java 10

var set = Set.copyOf(list);

有多种方法来获取一个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);

当我们使用collections . toset()时,它返回一个集合,并且根据文档:对于返回的set的类型、可变性、可序列化性或线程安全性没有保证。如果我们想要获得一个HashSet,那么我们可以使用另一种方法来获得一个set(检查set3)。

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

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

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

例子:

var set = Set.copyOf(list);

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

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

请记住,从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将一个List转换为一个Set

// 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());