Stream API 优化代码

Posted l_learning

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stream API 优化代码相关的知识,希望对你有一定的参考价值。

使用Java8中新特性Lambda表达式和流申明式处理数据集合,让代码更简洁

使用一个简单的员工类来学习使用方法

public class Employee 

        /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private int age;

    /**
     * 薪资
     */
    private double salary;

    /**
     * 部门
     */
    private String dept;

    public Employee(String name, int age, String dept, double salary) 
        this.name = name;
        this.age = age;
        this.dept = dept;
        this.salary = salary;
    

    //...省略

测试集合(模拟数据查询出来的数据)

List<Employee> stuList = new ArrayList<>();
stuList.add(new Employee("小明", 18, "开发部", 2000.00));
stuList.add(new Employee("小红", 20, "开发部", 2100.00));
stuList.add(new Employee("小强", 25, "测试部", 2200.00));

年龄小于25岁的员工姓名按年龄排序

List<String> result = stuList.stream()
                //筛选出年龄小于25岁的员工
                .filter(stu -> stu.getAge() < 25)
                //根据年龄进行排序
                .sorted(comparing(Employee::getAge))
                //获取员工姓名
                .map(Employee::getName)
                //转换为List
                .collect(Collectors.toList());

按员工部门进行分类

Map<String, List<Employee>> deptEmployee = stuList.stream()
                .collect(groupingBy(Employee::getDept));

filter的方法参数为一个条件,filter筛选年龄大于25岁的员工

List<Employee> employeeFilter = stuList.stream()
                .filter(i -> i.getAge() > 25)
                .collect(toList());

distinct去除重复元素(不能根据对象属性内容去重)

List<Employee> employeeDistinct = stuList.stream()
                .distinct()
                .collect(toList());

limit返回指定流个数,limit的参数值必须>=0

List<Employee> employeeLimit = stuList.stream()
                .limit(3)
                .collect(toList());

skip跳过流中的元素,skip的参数值必须>=0,从第三个元素开始取值

List<Employee> employeeSkip = stuList.stream()
                .skip(2)
                .collect(toList());

map方法类似一个迭代器,获取集合中的部门

List<String> dept = stuList.stream()
                .map(i->i.getDept())
                .collect(Collectors.toList());

flatMap流转换, 获取员工列表中部门,有多个部门的按逗号分割并去重

List<String> deptDistinct = stuList.stream()
                .map(w -> w.getDept().split(","))
                .flatMap(Arrays::stream)
                .distinct()
                .collect(Collectors.toList());

获取员工年龄中最小值

Optional<Integer> min = stuList.stream()
                .map(Employee::getAge)
                .min(Integer::compareTo);

获取员工年龄中最小值

OptionalInt min2 = stuList.stream()
                .mapToInt(Employee::getAge)
                .min();

获取员工年龄中最大值

Optional<Integer> max = stuList.stream()
                .map(Employee::getAge)
                .max(Integer::compareTo);

获取员工年龄中最大值

OptionalInt max2 = stuList.stream()
                .mapToInt(Employee::getAge)
                .max();

minBy获取员工年龄最小值

Optional<Integer> minBy = stuList.stream()
                .map(Employee::getAge)
                .collect(minBy(Integer::compareTo));

maxBy获取员工年龄最大值

Optional<Integer> maxBy = stuList.stream()
             	.map(Employee::getAge)
             	.collect(maxBy(Integer::compareTo));

reduce获取获取员工年龄最大值

Optional<Integer> reduceMin = stuList.stream()
                .map(Employee::getAge)
                .reduce(Integer::min);

reduce获取获取员工年龄最大值

Optional<Integer> reduceMax = stuList.stream()
                .map(Employee::getAge)
                .reduce(Integer::max);

求和, 员工的薪资之和

double sum = stuList.stream()
        .collect(summingDouble(Employee::getSalary));
double sum2 = stuList.stream()
        .map(Employee::getSalary)
        .reduce(0.00, Double::sum);
double sum3 = stuList.stream()
        .mapToDouble(Employee::getSalary)
        .sum();

averagingInt求员工年龄平均值

double average = stuList.stream()
                .collect(averagingInt(Employee::getAge));

summarizingInt同时求员工薪资总和、平均值、最大值、最小值

DoubleSummaryStatistics doubleSummaryStatistics = stuList.stream()
                .collect(summarizingDouble(Employee::getSalary));
//获取平均值
double summarizingDoubleAverage = doubleSummaryStatistics.getAverage();  
//获取最小值
double summarizingDoubleMin = doubleSummaryStatistics.getMin();  
//获取最大值
double summarizingDoubleMax = doubleSummaryStatistics.getMax();  
//获取总和
double summarizingDoubleSum = doubleSummaryStatistics.getSum();  

返回员工姓名List集合

List<String> nameList = stuList.stream()
                .map(Employee::getName)
                .collect(toList());

返回员工姓名Set集合

Set<String> nameSet = stuList.stream()
                .map(Employee::getName)
                .collect(toSet());

通过joining用逗号拼接员工姓名

String joinName = stuList.stream()
                .map(Employee::getName)
                .collect(joining(", "));

通过groupingBy进行员工部门分组

Map<String, List<Employee>> deptGroup = stuList.stream()
                .collect(groupingBy(Employee::getDept));

allMatch匹配所有,员工年龄都大于60

boolean allMatch = stuList.stream()
                .allMatch(i -> i.getAge() > 60);

anyMatch匹配其中一个,存在员工年龄大于60的员工

boolean anyMatch = stuList.stream()
                .anyMatch(i -> i.getAge() > 60);

noneMatch全部不匹配,员工年龄都小于60

boolean noneMatch = stuList.stream()
                .noneMatch(i -> i.getAge() > 60);

通过count统计员工个数

Long count = stuList.stream()
                .count();

通过counting统计员工个数

Long counting = stuList.stream()
                .collect(counting());

findFirst查找年龄大于60岁的第一个员工

Optional<Employee> findFirst = stuList.stream()
                .filter(i -> i.getAge() > 60)
                .findFirst();

findAny随机查找一个年龄大于60岁的第一个员工

Optional<Employee> resultFindAny = stuList.stream()
                .filter(i -> i.getAge() > 60)
                .findAny();

partitioningBy进行分区, 对年龄大于60的与小于等于60的分区

Map<Boolean, List<Employee>> partitioningBy = stuList.stream()
                .collect(partitioningBy(i -> i.getAge() > 60));

对一个集合中的值进行求和

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
//对一个集合中的值进行求和
int integerListSum = integerList.stream()
        .reduce(0, (a, b) -> (a + b));

//对一个集合中的值进行求和
int integerListSum2 = integerList.stream()
        .reduce(0, Integer::sum);

foreach进行元素遍历

stuList.stream().forEach(System.out::println);

以上是关于Stream API 优化代码的主要内容,如果未能解决你的问题,请参考以下文章

使用 Stream API 高逼格优化 Java 代码!

使用 Stream API 高逼格 优化 Java 代码!

Java8使用Stream API 优化 Java 代码

Java8使用Stream API 优化 Java 代码

Java8使用Stream API 优化 Java 代码

Java8使用Stream API 优化 Java 代码