Java 8 Stream API: 使用 Distinct 属性对对象列表去重
{"title":"Java 8 Stream API: 使用 Distinct 属性对对象列表去重","description":"本文介绍如何使用Java 8的Stream API根据对象的某个属性进行去重,并提供一个示例代码,演示如何根据Person对象的name属性对Person列表进行去重。","keywords":"Java 8, Stream API, 去重, Distinct, 对象列表, 属性, 示例代码, Person","content":"可以使用Java 8的Stream API来对对象列表根据某一属性进行去重。下面是一个示例代码:\n\njava\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\nclass Person {\n private String name;\n private int age;\n\n public Person(String name, int age) {\n this.name = name;\n this.age = age;\n } \n\n public String getName() {\n return name;\n } \n\n public int getAge() {\n return age;\n } \n}\n\npublic class Main {\n public static void main(String[] args) {\n List<Person> people = new ArrayList<>();\n people.add(new Person("John", 25));\n people.add(new Person("John", 30));\n people.add(new Person("Mary", 28));\n people.add(new Person("Mary", 35));\n people.add(new Person("John", 25));\n\n List<Person> distinctPeople = people.stream()\n .collect(Collectors.groupingBy(Person::getName))\n .values()\n .stream()\n .map(group -> group.get(0))\n .collect(Collectors.toList());\n\n distinctPeople.forEach(person -> System.out.println(person.getName() + " - " + person.getAge()));\n }\n}\n\n\n输出结果为:\n\nJohn - 25\nMary - 28\n
原文地址: https://www.cveoy.top/t/topic/p8iO 著作权归作者所有。请勿转载和采集!