开发手册 欢迎您!
软件开发者资料库

Java Stream Collectors的maxBy() minBy()、groupingBy()、partitioningBy()的使用

Stream是Java 8的新特性,基于lambda表达式,是对集合对象功能的增强,它专注于对集合对象进行各种高效、方便聚合操作或者大批量的数据操作,提高了编程效率和代码可读性。Collectors通常在Stream处理后,返回转换成集合类时使用,本文主要介绍Java Stream中Collectors.maxBy()/minBy()、Collectors.groupingBy()和Collectors.partitioningBy()的使用,,以及相关的示例代码。

1、Collectors.maxBy()/minBy()的使用

Collectors.maxBy()/minBy()可以根据指定的Comparator,计算stream中的最大值和最小值,例如,

import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {   public static class Person {     int age;     Person (int age) {         this.age = age;     }     public int getAge() {         return age;     }     public void setAge(int age) {         this.age = age;     }}public static void main(String[] args) {    List pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));    Optional maxByResult = pList.stream().map(p -> p.getAge()).collect(Collectors.maxBy(Comparator.naturalOrder()));    System.out.println("stream() maxByResult :" + maxByResult.get());    Optional minByResult = pList.stream().map(p -> p.getAge()).collect(Collectors.minBy(Comparator.naturalOrder()));    System.out.println("stream() minByResult :" + minByResult.get());    System.exit(0); //success  }}

2、Collectors.groupingBy()的使用

Collectors.groupingBy()根据指定的属性进行分组,并返回一个Map,例如,

import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {   public static class Person {     int age;     Person (int age) {         this.age = age;     }     public int getAge() {         return age;     }     public void setAge(int age) {         this.age = age;     }}public static void main(String[] args) {    List pList = Arrays.asList(new Person(11),new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));    Map> groupByResult = pList.stream()                .collect(Collectors.groupingBy(Person::getAge,Collectors.toSet()));    System.out.println("stream() groupByResult :" + groupByResult);    System.exit(0); //success  }}

3、Collectors.partitioningBy()的使用

Collectors.partitioningBy()返回一个Map,这个Map是以boolean值为key,将stream分成两部分,一部分是匹配PartitioningBy条件的,另一部分是不满足条件的:,如下,

import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {   public static class Person {     int age;     Person (int age) {         this.age = age;     }     public int getAge() {         return age;     }     public void setAge(int age) {         this.age = age;     }}public static void main(String[] args) {    List pList = Arrays.asList(new Person(11),new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));    Map> partitionResult = pList.stream()                .collect(Collectors.partitioningBy(p -> p.getAge() > 22));    System.out.println("stream() groupByResult :" + partitionResult);    System.exit(0); //success  }}

/script>