jdk8 Stream API用法

7 篇文章 0 订阅

Java8中有两大最为重要的改变。第一个是 Lambda表达式:另外个则是 Stream API(java.uti1. stream.* )

Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用 Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。也可以使用 Stream API来并行执行操作。简而言之Stream API提供了一种高效且易于使用的处理数据的方式。

什么是Stream

流(Stream)到底是什么呢?
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列;
集合讲的是数据,流讲的是计算。

注意:
① Stream自己不会存储元素。
② Stream不会改变源对象。相反,他们会返回一个持有结果的新 Stream
③ Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream的操作三个步骤

  • 创建 Stream
    一个数据源(如:集合、数组),获取一个流

  • 中间操作
    一个中间操作链,对数据源的数据进行处理

  • 终止操作(终端操作)
    一个终止操作,执行中间操作链,并产生结果
    在这里插入图片描述

获取stream流的4种方法

  1. Collection 提供了两个方法 stream() 与 parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream(); //获取一个顺序流
Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
  1. 通过 Arrays 中的 stream() 获取一个数组流
Integer[] nums = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(nums);
  1. 通过 Stream 类中静态方法 of()
Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);
  1. 创建无限流
//迭代
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
stream3.forEach(System.out::println);
		
//生成
Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
stream4.forEach(System.out::println);

Stream中间操作

操作多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”;

筛选与切片

  • filter——接收 Lambda , 从流中排除某些元素。
  • limit——截断流,使其元素不超过给定数量。
  • skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
  • distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

Employee类:

List<Employee> emps = Arrays.asList(
        new Employee(101, "张三", 18, 9500.00),
        new Employee(102, "李四", 36, 15000.00),
        new Employee(103, "王五", 40, 18000.00),
        new Employee(104, "赵六", 18, 6000.00),
        new Employee(105, "田七", 20, 4500.00),
        new Employee(104, "福八", 22, 8000.00)
);

filter 测试:打印年龄小于等于35的员工

public void test2(){
    //所有的中间操作不会做任何的处理
    Stream<Employee> stream = emps.stream()
        .filter((e) -> e.getAge() <= 35);

    //只有终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
    stream.forEach(System.out::println);
}

limit测试:打印工资大于等于5000的前2个

public void test4(){
    emps.stream()
        .filter(e -> e.getSalary() >= 5000)
        .limit(2)
        .forEach(System.out::println); 
}

skip(n) 测试:
打印工资大于等于5000的并且跳过前2个

public void test5(){
    emps.parallelStream()
        .filter((e) -> e.getSalary() >= 5000)
        .skip(2)
        .forEach(System.out::println); 
}

distinct 测试:通过流所生成元素的 hashCode() 和 equals() 去除重复元素

public void test6(){
    emps.stream()
        .distinct()
        .forEach(System.out::println);
    
   /*  
    以下是Employee equals和hashCode的重写方法,快捷键生成,可不看
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id &&
                age == employee.age &&
                Double.compare(employee.salary, salary) == 0 &&
                Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age, salary);
    }*/
}

映射
map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

排序
sorted()——自然排序
sorted(Comparator com)——定制排序

public void test2(){
    emps.stream()
        .map(Employee::getName)
        .sorted()
        .forEach(System.out::println);

    System.out.println("------------------------------------");

    emps.stream()
        .sorted((x, y) -> {
            if(x.getAge() == y.getAge()){
                return x.getName().compareTo(y.getName());
            }else{
                return Integer.compare(x.getAge(), y.getAge());
            }
        }).forEach(System.out::println);
}

Stream终止操作

allMatch——检查是否匹配所有元素
anyMatch——检查是否至少匹配一个元素
noneMatch——检查是否没有匹配的元素
findFirst——返回第一个元素
findAny——返回当前流中的任意元素
count——返回流中元素的总个数
max——返回流中最大值
min——返回流中最小值

Employee数组:伪数据

List<Employee> emps = Arrays.asList(
        new Employee(101, "张三", 18, 9999.00, Status.FREE),
        new Employee(102, "李四", 33, 6000.00, Status.BUSY),
        new Employee(103, "王五", 28, 3000.00, Status.VOCATION),
        new Employee(104, "赵六", 18, 7000.00, Status.BUSY),
        new Employee(104, "赵六", 18, 7000.00, Status.FREE),
        new Employee(104, "赵六", 18, 7000.00, Status.FREE),
        new Employee(105, "田七", 38, 5000.00, Status.BUSY)
);

allMatch、anyMatch、noneMatch测试

@Test
public void test1(){
    //检查是否匹配所有元素
    boolean bl = emps.stream()
        .allMatch((e) -> e.getStatus().equals(Status.BUSY));
    System.out.println(bl); // false

    //检查是否至少匹配一个元素
    boolean bl1 = emps.stream()
        .anyMatch((e) -> e.getStatus().equals(Status.BUSY));
    System.out.println(bl1); //true

    //检查是否没有匹配的元素
    boolean bl2 = emps.stream()
        .noneMatch((e) -> e.getStatus().equals(Status.BUSY));
    System.out.println(bl2); //false
}

findFirst、findAny测试

@Test
public void test2(){
    // findFirst 返回第一个元素
    // Optional类是jdk1.8新增的,可以防止空指针异常
    Optional<Employee> op = emps.stream()
        .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
        .findFirst();
    System.out.println(op.get());

    // findAny 返回当前流中的任意元素
    Optional<Employee> op2 = emps.parallelStream()
        .filter((e) -> e.getStatus().equals(Status.FREE))
        .findAny();
    System.out.println(op2.get());
}

count、max、min 测试

@Test
public void test3(){
    //count 返回流中元素的总个数
    long count = emps.stream()
                     .filter((e) -> e.getStatus().equals(Status.FREE))
                     .count();
    System.out.println(count);

    // max 返回流中最大值
    Optional<Double> op = emps.stream()
        .map(Employee::getSalary)
        .max(Double::compare);
    System.out.println(op.get());

    // min 返回流中最小值
    Optional<Employee> op2 = emps.stream()
        .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
    System.out.println(op2.get());
}

注意:流进行了终止操作后,不能再次使用

@Test
public void test4(){
    Stream<Employee> stream = emps.stream()
     .filter((e) -> e.getStatus().equals(Status.FREE));
    long count = stream.count();
    
    //下面不能再进行终止操作
    stream.map(Employee::getSalary)
        .max(Double::compare);
}
归约

reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。

测试1:数组里面的数相加

@Test
public void test1(){
    List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

    Integer sum = list.stream()
        .reduce(0, (x, y) -> x + y);
    System.out.println(sum);

    Optional<Double> op = emps.stream()
        .map(Employee::getSalary)
        .reduce(Double::sum);
    System.out.println(op.get());
}

测试2:搜索名字中 “六” 出现的次数

@Test
public void test2(){
    Optional<Integer> sum = emps.stream()
        .map(Employee::getName)
        .flatMap(TestStreamAPI1::filterCharacter)
        .map((ch) -> {
            if(ch.equals('六'))
                return 1;
            else 
                return 0;
        }).reduce(Integer::sum);

    System.out.println(sum.get());
}
收集

collect,将流转换为其他形式。接收一个Collector接口的实现,用于给 Stream!中元素做汇总的方法;

测试1:分别以list,set,指定集合收集

public void test3(){
    //收集Employee的人员名字放入list集合
    List<String> list = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.toList());
    list.forEach(System.out::println);

    //收集Employee的人员名字放入set集合
    Set<String> set = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.toSet());
    set.forEach(System.out::println);

    //放到指定的集合中
    HashSet<String> hs = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.toCollection(HashSet::new));
    hs.forEach(System.out::println);
}

测试2:

public void test4(){
    //取出员工的最大工资
    Optional<Double> max = emps.stream()
        .map(Employee::getSalary)
        .collect(Collectors.maxBy(Double::compare));
    System.out.println(max.get()); //9999.0

    //查询最小工资的员工信息
    Optional<Employee> op = emps.stream()
        .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
    System.out.println(op.get()); //

    //求所有员工的工资总和
    Double sum = emps.stream()
        .collect(Collectors.summingDouble(Employee::getSalary));
    System.out.println(sum);

    //求工资的平均值
    Double avg = emps.stream()
        .collect(Collectors.averagingDouble(Employee::getSalary));
    System.out.println(avg);

    //求员工总数
    Long count = emps.stream()
        .collect(Collectors.counting());
    System.out.println(count);

    //获得汇总各种数据的对象
    DoubleSummaryStatistics dss = emps.stream()
        .collect(Collectors.summarizingDouble(Employee::getSalary));
    System.out.println(dss.getMax());
    System.out.println(dss.getMin());
    System.out.println(dss.getSum());
}
分组
//根据员工状态进行分组
@Test
public void test5(){
    Map<Status, List<Employee>> map = emps.stream()
        .collect(Collectors.groupingBy(Employee::getStatus));

    System.out.println(map);
}

多级分组

//根据员工状态进行分组,在根据年龄进行分组
@Test
public void test6(){
    Map<Status, Map<String, List<Employee>>> map = emps.stream()
        .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
            if(e.getAge() >= 60)
                return "老年";
            else if(e.getAge() >= 35)
                return "中年";
            else
                return "成年";
        })));

    System.out.println(map);
}
分区
//根据工资范围进行分区
@Test
public void test7(){
    Map<Boolean, List<Employee>> map = emps.stream()
        .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));

    System.out.println(map);
}
连接
@Test
public void test8(){
    //将所有员工名字,以“,”进行连接,前缀----,后缀****
    String str = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.joining("," , "----", "****"));

    System.out.println(str);
}
Collectors 包下的归约方法
@Test
public void test9(){
    Optional<Double> sum = emps.stream()
        .map(Employee::getSalary)
        .collect(Collectors.reducing(Double::sum));

    System.out.println(sum.get());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值