JAVA8 STREAM COLLECT GROUPBY分组实例解析
这篇文章主要介绍了JAVA8STREAMCOLLECTGROUPBY分组实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
实体类People,有个返回list的buildPeopleList方法,方便测试。
importlombok.AllArgsConstructor; importlombok.Builder; importlombok.Data; importlombok.NoArgsConstructor; importjava.util.ArrayList; importjava.util.Arrays; importjava.util.List; /** *@author:rhyme *@date:2019-09-2617:31 *@topic:"主题" *@description:"描述" */ @Data @NoArgsConstructor @AllArgsConstructor @Builder publicclassPeople{ privateStringname; privateStringcharacter; privateStringsex; privateintage; publicstaticPeoplebuildDefault(){ returnPeople.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build(); } publicstaticListbuildPeopleList(){ Peoplep1=People.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build(); Peoplep2=People.builder().name("Zhang").character("optimistic").sex("female").age(23).build(); Peoplep3=People.builder().name("Hu").character("shy").sex("female").age(25).build(); Peoplep4=People.builder().name("Y").character("Righteous").sex("male").age(24).build(); returnnewArrayList<>(Arrays.asList(p1,p2,p3,p4)); } }
测试类GroupByTest,分别根据性别分组,统计各个性别人数,以及各个性别映射姓名。
importorg.junit.After; importorg.junit.Before; importorg.junit.Test; importorg.springframework.util.CollectionUtils; importjava.util.List; importjava.util.Map; importjava.util.function.BiConsumer; importjava.util.stream.Collectors; /** *@author:rhyme *@date:2019-10-1415:59 *@topic:"主题" *@description:"描述" */ publicclassGroupByTest{ privateListpeople; privateBiConsumersoutKV; privateMapresult; @Before publicvoidinit(){ people=People.buildPeopleList(); soutKV=(k,v)->System.out.println(k+":"+v); } @After publicvoidsoutResult(){ if(!CollectionUtils.isEmpty(result)){ result.forEach(soutKV); } } /** *根据性别分组 */ @Test publicvoidgroupBySex(){ result=people.stream().collect( Collectors.groupingBy(People::getSex) ); } /** *分别统计不同性别各自的人数 */ @Test publicvoidgroupBySexCount(){ result=people.stream().collect( Collectors.groupingBy(People::getSex,Collectors.counting() )); } /** *分别统计不同性别各自的name列表 */ @Test publicvoidgroupBySexName(){ result=people.stream().collect( Collectors.groupingBy( People::getSex, Collectors.mapping(People::getName,Collectors.toSet()) )); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。