java8 group count_JAVA8 STREAM COLLECT GROUPBY分组实例解析

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:50   1036   0

2fdcc75eeeb0c8fcc46132fa9f53b255.png

这篇文章主要介绍了JAVA8 STREAM COLLECT GROUPBY分组实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

实体类People,有个返回list的buildPeopleList方法,方便测试。

import lombok.AllArgsConstructor;

import lombok.Builder;

import lombok.Data;

import lombok.NoArgsConstructor;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

/**

* @author: rhyme

* @date: 2019-09-26 17:31

* @topic: "主题"

* @description: "描述"

*/

@Data

@NoArgsConstructor

@AllArgsConstructor

@Builder

public class People {

private String name;

private String character;

private String sex;

private int age;

public static People buildDefault() {

return People.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build();

}

public static List buildPeopleList() {

People p1 = People.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build();

People p2 = People.builder().name("Zhang").character("optimistic").sex("female").age(23).build();

People p3 = People.builder().name("Hu").character("shy").sex("female").age(25).build();

People p4 = People.builder().name("Y").character("Righteous").sex("male").age(24).build();

return new ArrayList<>(Arrays.asList(p1, p2, p3, p4));

}

}

测试类GroupByTest,分别根据性别分组,统计各个性别人数,以及各个性别映射姓名。

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

import org.springframework.util.CollectionUtils;

import java.util.List;

import java.util.Map;

import java.util.function.BiConsumer;

import java.util.stream.Collectors;

/**

* @author: rhyme

* @date: 2019-10-14 15:59

* @topic: "主题"

* @description: "描述"

*/

public class GroupByTest {

private List people;

private BiConsumer soutKV;

private Map result;

@Before

public void init() {

people = People.buildPeopleList();

soutKV = (k, v) -> System.out.println(k + ":" + v);

}

@After

public void soutResult() {

if (!CollectionUtils.isEmpty(result)) {

result.forEach(soutKV);

}

}

/**

* 根据性别分组

*/

@Test

public void groupBySex() {

result = people.stream().collect(

Collectors.groupingBy(People::getSex)

);

}

/**

* 分别统计不同性别各自的人数

*/

@Test

public void groupBySexCount() {

result = people.stream().collect(

Collectors.groupingBy(People::getSex, Collectors.counting()

));

}

/**

* 分别统计不同性别各自的name列表

*/

@Test

public void groupBySexName() {

result = people.stream().collect(

Collectors.groupingBy(

People::getSex,

Collectors.mapping(People::getName, Collectors.toSet())

));

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持云海天教程。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP