Java Stream 分组后排序:使用 Collectors.groupingBy 和 Collectors.toMap
在Java中,可以使用Collectors.groupingBy()方法将Stream中的元素按照指定的条件分组。然后,可以使用Collectors.toMap()方法将分组后的结果转换为Map,并进行排序。\n\n下面是一个示例代码,演示了如何使用Stream分组后进行排序:\n\njava\nimport java.util.*;\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 @Override\n public String toString() {\n return "Person{" +\n "name='" + name + "'" +\n ", age=" + age +\n '}';\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n List<Person> persons = Arrays.asList(\n new Person("John", 20),\n new Person("Jane", 25),\n new Person("Mike", 30),\n new Person("Jane", 35),\n new Person("John", 40)\n );\n\n Map<String, List<Person>> groupedPersons = persons.stream()\n .collect(Collectors.groupingBy(Person::getName));\n\n Map<String, List<Person>> sortedGroupedPersons = groupedPersons.entrySet().stream()\n .sorted(Map.Entry.comparingByKey())\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, \n (oldValue, newValue) -> oldValue, LinkedHashMap::new));\n\n System.out.println(sortedGroupedPersons);\n }\n}\n\n\n输出结果为:\n\n\n{Jane=[Person{name='Jane', age=25}, Person{name='Jane', age=35}], John=[Person{name='John', age=20}, Person{name='John', age=40}], Mike=[Person{name='Mike', age=30}]}\n\n\n在上面的示例中,首先将persons列表中的元素按照Person::getName进行分组,得到一个Map<String, List<Person>>。然后,使用entrySet().stream()将Map转换为Stream,并使用sorted()方法对其进行排序。最后,使用toMap()方法将排序后的结果转换为Map,并指定了排序后的Map的实现类为LinkedHashMap,以保证排序的顺序被保留。\n\n注意,上述示例中的Person类只是一个简单的示例,你可以根据实际需求修改和扩展它。
原文地址: https://www.cveoy.top/t/topic/ow1R 著作权归作者所有。请勿转载和采集!