假设有一个名为Person的类,其中包含属性name: java&#x0A;public class Person {&#x0A; private String name;&#x0A;&#x0A; public Person(String name) {&#x0A; this.name = name;&#x0A; }&#x0A;&#x0A; public String getName() {&#x0A; return name;&#x0A; }&#x0A;}&#x0A; 然后我们有一个List,我们要根据name属性去重,并且将去重后的名称组合成一个新的List。 可以使用Java 8的Stream API来解决这个问题。下面是一个示例代码: java&#x0A;import java.util.ArrayList;&#x0A;import java.util.List;&#x0A;import java.util.stream.Collectors;&#x0A;&#x0A;public class Main {&#x0A; public static void main(String[] args) {&#x0A; List<Person> personList = new ArrayList<>();&#x0A; personList.add(new Person("Alice"));&#x0A; personList.add(new Person("Bob"));&#x0A; personList.add(new Person("Alice"));&#x0A; personList.add(new Person("Charlie"));&#x0A;&#x0A; List<String> distinctNames = personList.stream()&#x0A; .map(Person::getName) // 提取name属性&#x0A; .distinct() // 去重&#x0A; .collect(Collectors.toList()); // 转换成List<String>&#x0A;&#x0A; System.out.println(distinctNames);&#x0A; }&#x0A;}&#x0A; 输出结果为: &#x0A;[Alice, Bob, Charlie]&#x0A; 在代码中,我们使用了stream()方法将List转换为一个Stream对象,然后使用map()方法将Person对象映射为其name属性,使用distinct()方法去除重复的name,最后使用collect()方法将Stream转换为List

Java 8 使用Stream API 去重List对象并提取属性为新List - 代码示例

原文地址: https://www.cveoy.top/t/topic/qeUo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录