Java8 Stream Collectors 使用

版权声明:“假装、是个有灵魂的程序员” —— Go Big Or Go Home https://blog.csdn.net/u011663149/article/details/88536588

前言: 

     java.util.stream.Collectors.* 类为我们提供了丰富的对流的操作,对此写了一些较为测试案例:

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ConcurrentMap;

import static java.util.Comparator.comparingDouble;
import static java.util.stream.Collectors.*;

/**
 * @author DHing
 */
public class StreamCollector {

    public static void main(String[] args) {

        Employee john = new Employee("E123", "张三", 200.99, "财务");
        Employee south = new Employee("E223", "李四", 299.99, "开发");
        Employee reet = new Employee("E133", "王五", 300.99, "测试");
        Employee prateema = new Employee("E143", "赵麻子", 300.99, "运维");
        Employee yogen = new Employee("E323", "孙大圣", 200.99, "产品");

        List<Employee> employees = Arrays.asList(john, south, reet, prateema, yogen);

        // 求平均 average-Double/Int/Long
        Double averageSalary = employees.stream().collect(averagingDouble(Employee::getSalary));
        System.out.println("平均:"+ averageSalary);

        // 求和
        Double totalSalary = employees.stream().collect(summingDouble(Employee::getSalary));
        System.out.println("求和:" + totalSalary);

        // 计算所有统计数据
        DoubleSummaryStatistics statistics = employees.stream().collect(summarizingDouble(Employee::getSalary));
        System.out.println("Average: " + statistics.getAverage() + ", Total: " + statistics.getSum() + ", Max: " + statistics.getMax() + ", Min: "+ statistics.getMin());

        //计算最高工资
        Double maxSalary = employees.stream().collect(collectingAndThen(maxBy(comparingDouble(Employee::getSalary)), emp -> emp.get().getSalary()));
        System.out.println(maxSalary);

        // 用CollectionAndThen格式化结果
        String avgSalary = employees.stream()
                .collect(collectingAndThen(averagingDouble(Employee::getSalary), new DecimalFormat("'¥'0.000")::format));
        System.out.println(avgSalary);

        // 映射数据转换
        List<String> employeeNames = employees.stream().collect(mapping(Employee::getName, toList())); //employees.stream().map(Employee::getName).collect(toList());
        System.out.println(employeeNames);

        // 输出字符串
        String employeeNamesStr = employees.stream().map(Employee::getName).collect(joining(","));
        System.out.println(employeeNamesStr);

        // 输出字符串 进行格式化处理
        employeeNamesStr = employees.stream().map(Employee::getName).collect(joining(", ", "Employees = {", "}"));
        System.out.println(employeeNamesStr);

        // 条件分组
        Map<String, List<Employee>> deptEmps = employees.stream().collect(groupingBy(Employee::getDepartment));
        System.out.println(deptEmps);

        // 将数据分组,并对其进行条件计数
        Map<String, Long> deptEmpsCount = employees.stream().collect(groupingBy(Employee::getDepartment, counting()));
        System.out.println(deptEmpsCount);

        // 用条件分组数据,用键排序平均值
        Map<String, Double> averageSalaryDeptSorted = employees.stream().collect(groupingBy(Employee::getDepartment, TreeMap::new, averagingDouble(Employee::getSalary)));
        System.out.println(averageSalaryDeptSorted);

        // 返回Concurrenthashmap 
        ConcurrentMap<String, Long> collect = employees.stream().collect(groupingByConcurrent(Employee::getDepartment, counting()));
        System.out.println(collect);

        // 取最大
        Optional<Employee> employeeWithMaxSalary = employees.stream().collect(maxBy(comparingDouble(Employee::getSalary)));
        employeeWithMaxSalary.ifPresent(System.out::println);

        // 分区数据
        Map<Boolean, List<Employee>> portionedEmployees = employees.stream().collect(partitioningBy(e -> e.getSalary() > averageSalary));
        System.out.println(portionedEmployees);
    }
}

class Employee {
    private String empId;
    private String name;
    private Double salary;
    private String department;

    public Employee(String empId, String name, Double salary, String department) {
        this.empId = empId;
        this.name = name;
        this.salary = salary;
        this.department = department;
    }

    public String getEmpId() {
        return empId;
    }

    public String getName() {
        return name;
    }

    public Double getSalary() {
        return salary;
    }

    public String getDepartment() {
        return department;
    }

    @Override
    public String toString() {
        return "{" +
                "empId='" + empId + '\'' +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", department='" + department + '\'' +
                '}';
    }
}

更多Java8操作可参考: https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/

      Stream集合可参考:https://blog.csdn.net/u011663149/article/details/86743930

      GroupBy可参考:    https://blog.csdn.net/u011663149/article/details/87883739

                


猜你喜欢

转载自blog.csdn.net/u011663149/article/details/88536588
今日推荐