Java8 Stream API

package com.xx;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
 * @author xx
 * DateTime: 2019/11/18 17:02
 * Description: Stream
 *      中间操作:
 *      filter:接收Lambda,过滤某些元素
 *      limit:保留前几个元素
 *      skip:跳过前几个元素
 *      distinct:通过hashCode()和equals()去除重复对象
 *
 *      map:映射,接收Lambda,将元素转换成其他形式或提取信息,接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
 *      flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流链接成一个流
 *
 *      sorted:自然排序
 *      sorted(Comparator com):定制排序
 *
 *      终止操作:
 *      allMatch:检查是否匹配所有元素
 *      anyMatch:检查是否至少匹配一个元素
 *      noneMatch:检查是否没有匹配所有元素
 *      findFirst:返回第一个元素
 *      findAny:返回当前流中任意元素
 *      count:返回流中元素的总个数
 *      max:返回流中最大值
 *      min:返回流中最小值
 *
 *      reduce:归约,可以将流中元素反复结合起来,得到一个值
 *
 *      collect:收集,将流转化为其他形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
 */
public class StreamApiDemo {

    private static List<Employee> employees = Arrays.asList(
            new Employee("张三", 18, 4000.9, Status.FREE),
            new Employee("李四", 19, 5000.9, Status.BUSY),
            new Employee("王五", 20, 6000.9, Status.VOCATION),
            new Employee("赵六", 21, 7000.9, Status.FREE),
            new Employee("田七", 22, 8000.9, Status.BUSY),
            new Employee("赵六", 21, 7000.9, Status.VOCATION),
            new Employee("赵六", 21, 7000.9, Status.FREE),
            new Employee("赵六", 21, 7000.9, Status.BUSY),
            new Employee("赵六", 21, 7000.9, Status.VOCATION),
            new Employee("赵六", 21, 7000.9, Status.FREE)
    );

    public static void main(String[] args) {
        employees.stream().filter( (e) -> e.getAge() > 20).distinct().forEach(System.out::println);
//        employees.stream().filter( (e) -> {
//            System.out.println("Stream API 中间操作");
//            return e.getAge() > 20;
//        }).forEach(System.out::println);

        List<String> list = Arrays.asList("ddd", "bbb", "ccc", "aaa");


        // 变成大写
        list.stream().map( (str) -> str.toUpperCase()).forEach(System.out::println);

        // 上方->可以使用::简化代码
        list.stream().map(String::toUpperCase).forEach(System.out::println);

        // 过滤,只保留人名
        employees.stream().map(Employee::getName).distinct().forEach(System.out::println);

        // 自然排序
        System.out.println("------------------排序---------------------");
        list.stream().sorted().forEach(System.out::println);

        // 定制排序
        employees.stream().distinct().sorted( (e1, e2) -> {
            if(e1.getAge() == e2.getAge()){
                return Double.compare(e1.getSalary(), e2.getSalary());
            }else{
                return -Integer.compare(e1.getAge(), e2.getAge());
            }
        }).forEach(System.out::println);

        // 判断是否匹配所有元素
        boolean bool = employees.stream().allMatch((e) -> e.getStatus().equals(Status.BUSY));
        System.out.println("判断是否匹配所有元素:"+bool);

        // 判断是否至少匹配一个元素
        boolean bool1 = employees.stream().anyMatch((e) -> e.getStatus().equals(Status.BUSY));
        System.out.println("判断是否至少匹配一个元素:"+bool1);

        // 判断是否所有元素都不匹配
        boolean bool2 = employees.stream().noneMatch((e) -> e.getStatus().equals(Status.BUSY));
        System.out.println("判断是否所有元素都不匹配:"+bool2);

        // 获取第一个元素
        Optional<Employee> first = employees.stream().findFirst();
        System.out.println("获取第一个元素:"+first.get());

        // 过滤返回Status为FREE的任意元素返回
        Optional<Employee> any = employees.stream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny();
        System.out.println("过滤返回Status为FREE的任意元素返回:"+any);

        // 统计元素个数
        long count = employees.stream().count();
        System.out.println("统计元素个数:"+count);

        // 返回最大值
        employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        employees.stream().max(Comparator.comparingDouble(Employee::getSalary));

        // 返回最少的工资数
        Double minSalary = employees.stream().map(Employee::getSalary).max(Double::compare).get();

        // 归约
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer reduce = integerList.stream().reduce(0, (x, y) -> x + y);
        System.out.println(reduce);

        // 计算员工工资总和,如果处理后的值存在空值的可能性便返回Optional类型
        employees.stream().map(Employee::getSalary).reduce(Double::sum);

        // 提取姓名集合
        List<String> nameList = employees.stream().map(Employee::getName).collect(Collectors.toList());
        // 提取到特殊的集合中
        HashSet<String> nameList1 = employees.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));
        nameList.forEach(System.out::println);

        // 计数
        Long collect = employees.stream().collect(Collectors.counting());
        long collect1 = employees.stream().count();
        System.out.println("计数:"+collect);
        System.out.println("计数:"+collect1);

        // 计算工资平均值
        Double getAvgSalary = employees.stream().collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println("工资平均值:"+getAvgSalary);

        // 收集,获取计数,工资总和,最小值,平均值,最大值
        DoubleSummaryStatistics getSumSalary = employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
        System.out.println("收集,计数,工资总和,最小值,平均值,最大值:"+getSumSalary);

        // 分组
        Map<Status, List<Employee>> groupMap = employees.stream().collect(Collectors.groupingBy(Employee::getStatus));
        System.out.println("分组"+groupMap);

        // 多级分组
        Map<Status, Map<String, List<Employee>>> moreGroupMap = employees.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
            // 手动编写分组条件
            if (e.getAge() <= 30) {
                return "青年";
            } else if (e.getAge() <= 50) {
                return "中年";
            } else {
                return "老年";
            }
        })));
        System.out.println("多级分组:"+moreGroupMap);

        // 分区
        Map<Boolean, List<Employee>> partitionMap = employees.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() > 8000));
        System.out.println("条件分区"+partitionMap);

        // 连接
        String collect2 = employees.stream().distinct().map(Employee::getName).collect(Collectors.joining(","));
        System.out.println("连接字符串:"+collect2);

    }

    /**
     * 获取Stream流
     */
    public void getStream() {
        // 1.通过Collection集合提供的stream() 或者 parallelStream 创建Stream
        List<String> list = new ArrayList<>();
        Stream<String> stream = list.stream();

        // 2.通过Arrays中的静态方法stream() 获取数组流
        int[] arr = {1, 2, 3};
        IntStream stream1 = Arrays.stream(arr);

        // 3.通过Stream类中的静态方法of()
        Stream<int[]> stream2 = Stream.of(arr);

        // 4.创建无限流
        Stream.generate( () -> new Random().nextInt(100)).limit(100).forEach(System.out::println);

    }


}
package com.xx;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author xx
 * DateTime: 2019/11/9 11:45
 * Description: No Description
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    private String name;
    private int age;
    private double salary;
    private Status status;

}
package com.xx;

/**
 * @author xx
 * DateTime: 2019/11/19 10:31
 * Description: No Description
 */
public enum Status {
    FREE,BUSY,VOCATION;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值