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


当前回答

在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<Foo> foo = new HashSet<Foo>(myList);

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

例子:

var set = Set.copyOf(list);

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

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

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

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

请记住,从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()); 

使用构造函数的最好方法

Set s= new HashSet(list);

在java 8中,你也可以使用stream api::

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