Java 8 使用Stream API 去重List对象并提取属性为新List - 代码示例
假设有一个名为Person的类,其中包含属性name:
java
public class Person {
 private String name;

 public Person(String name) {
 this.name = name;
 }

 public String getName() {
 return name;
 }
}

然后我们有一个Listjava
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
 public static void main(String[] args) {
 List<Person> personList = new ArrayList<>();
 personList.add(new Person("Alice"));
 personList.add(new Person("Bob"));
 personList.add(new Person("Alice"));
 personList.add(new Person("Charlie"));

 List<String> distinctNames = personList.stream()
 .map(Person::getName) // 提取name属性
 .distinct() // 去重
 .collect(Collectors.toList()); // 转换成List<String>

 System.out.println(distinctNames);
 }
}

输出结果为:

[Alice, Bob, Charlie]

在代码中,我们使用了stream()方法将List转换为一个Stream对象,然后使用map()方法将Person对象映射为其name属性,使用distinct()方法去除重复的name,最后使用collect()方法将Stream转换为List
原文地址: https://www.cveoy.top/t/topic/qeUo 著作权归作者所有。请勿转载和采集!