普通对象列表进行分组
@Data
public class People { String name; Integer age; Integer sex; Double height; Double weight;
} public class ListGroupTest { public static void main ( String [ ] args) { List < People > list = new ArrayList < > ( ) ; Random random = new Random ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { People people = new People ( ) ; people. setName ( "name" + i) ; people. setAge ( random. nextInt ( 50 ) ) ; people. setSex ( random. nextInt ( 1 ) ) ; people. setHeight ( random. nextDouble ( ) ) ; people. setWeight ( random. nextDouble ( ) ) ; list. add ( people) ; } Map < Integer , List < People > > collect = list. stream ( ) . collect ( Collectors . groupingBy ( People :: getSex ) ) ; }
}
map或jsonObject 列表进行分组
Map map1 = new HashMap ( ) ; map1. put ( "schoolId" , 1 ) ; map1. put ( "gradeId" , 1 ) ; map1. put ( "city" , 1 ) ; Map map2 = new HashMap ( ) ; map2. put ( "schoolId" , 2 ) ; map2. put ( "gradeId" , 2 ) ; map2. put ( "city" , 2 ) ; Map map5 = new HashMap ( ) ; map5. put ( "schoolId" , 3 ) ; map5. put ( "gradeId" , 3 ) ; map5. put ( "city" , 3 ) ; List < Map > list1 = new ArrayList < > ( ) ; list1. add ( map1) ; list1. add ( map2) ; list1. add ( map5) ;
Map < Object , List < Map > > mapGroup1 = list1. stream ( ) . collect ( Collectors . groupingBy ( o -> o. get ( "schoolId" ) ) ) ;
Map < String , List < Map > > mapGroup2 = list1. stream ( ) . collect ( Collectors . groupingBy ( o -> "-" + o. get ( "schoolId" ) + '-' + o. get ( "gradeId" ) ) ) ; List < String > paramsList = new ArrayList ( ) ;
paramsList. add ( "schoolId" ) ;
paramsList. add ( "gradeId" ) ;
paramsList. add ( "city" ) ;
Map < String , List < Map > > mapGroup3 = list1. stream ( ) . collect ( Collectors . groupingBy ( o -> StringUtils . join ( paramsList. stream ( ) . map ( key -> "-" + o. get ( key) ) . collect ( Collectors . toList ( ) ) , "" ) ) ) ;