Java新特性玩转JDK8之收集器 group by分组
功能
示例
public class Student {
private String province;
private int age;
public Student ( String province, int age) {
this . age = age;
this . province = province;
}
public String getProvince ( ) {
return province;
}
public void setProvince ( String province) {
this . province = province;
}
public int getAge ( ) {
return age;
}
public void setAge ( int age) {
this . age = age;
}
}
public class Main {
public static void main ( String[ ] args) {
List< Student> students = Arrays. asList ( new Student ( "广东" , 23 ) ,
new Student ( "广东" , 24 ) ,
new Student ( "广东" , 23 ) ,
new Student ( "北京" , 22 ) ,
new Student ( "北京" , 20 ) ,
new Student ( "北京" , 20 ) ,
new Student ( "海南" , 25 ) ) ;
Map< String, List< Student> > listMap = students. stream ( ) . collect ( Collectors. groupingBy ( obj - > obj. getProvince ( ) ) ) ;
listMap. forEach ( ( key, value) - > {
System. out. println ( "========" ) ;
System. out. println ( key) ;
value. forEach ( obj - > {
System. out. println ( obj. getAge ( ) ) ;
} ) ;
} ) ;
}
}
原文地址:https://www.yuque.com/haomingzi-kowv5/pmcs3t/ypg81a