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

分組java

視頻講解 https://www.bilibili.com/video/av78225682/

EmployeeTestCase.javaide

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));
}

結果:spa

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分鐘視頻學習
code

相關文章
相關標籤/搜索