其他分享
首页 > 其他分享> > Stream系列(十三) GroupingBy方法使用

Stream系列(十三) GroupingBy方法使用

作者:互联网

分组

视频讲解 https://www.bilibili.com/video/av78225682/

 

EmployeeTestCase.java
package com.example.demo;

import lombok.extern.log4j.Log4j2;
import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Log4j2
public class EmployeeTestCase extends BaseTestCase {
    @Test
    public void groudBy(){
        //根据薪酬获取员工列表
        Map<Double,List<Employee>> map = list.stream()
                .collect(Collectors.groupingBy(Employee::getSalary));
        System.out.println("map:"+map);
        //根据薪酬获取员工数量
        Map<Double,Long> map2 = list.stream()
                .collect(Collectors.groupingBy(Employee::getSalary,Collectors.counting()));
        System.out.println("map2:"+map2);
        //根据薪酬获取员工薪酬总数
        Map<Double,Double> map3 = list.stream()
                .collect(Collectors.groupingBy(Employee::getSalary,Collectors.summingDouble(Employee::getSalary)));
        System.out.println("map3:"+map3);
    }
}
BaseTestCase.java
package com.example.demo;

import java.util.Arrays;
import java.util.List;

public class BaseTestCase {
    protected static final List<Employee> list = Arrays.asList(
            new Employee(1, "Alex", 1000),
            new Employee(2, "Michael", 2000),
            new Employee(3, "Jack", 1500),
            new Employee(4, "Owen", 1500),
            new Employee(5, "Denny", 2000));
}

结果:

map:{1500.0=[Employee(id=3, name=Jack, salary=1500.0), Employee(id=4, name=Owen, salary=1500.0)], 2000.0=[Employee(id=2, name=Michael, salary=2000.0), Employee(id=5, name=Denny, salary=2000.0)], 1000.0=[Employee(id=1, name=Alex, salary=1000.0)]}
map2:{1500.0=2, 2000.0=2, 1000.0=1}
map3:{1500.0=3000.0, 2000.0=4000.0, 1000.0=1000.0}

 关注公众号,坚持每天3分钟视频学习

 

 

标签:Collectors,java,Stream,GroupingBy,十三,util,1500.0,Employee,import
来源: https://www.cnblogs.com/JavaWeiBianCheng/p/11994588.html