JAVA 8新特性(四):Stream

一、介绍

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对 集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作

使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数 据库查询。也可以使用 Stream API 来并行执行操作。简而言之, Stream API 供了一种高效且易于使用的处理数据的方式。

二、什么是流

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

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

三、Stram 的操作三个步骤

1、创建 Stream

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

2、中间操作

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

3、终止操作(终端操作)

    一个终止操作,执行中间操作链,并产生结果

在这里插入图片描述

四、创建Stream的四种方式

第一种:通过 Collection 系列集合提供的方法 stream() 或者 parallelStream()
Java8 中的 Collection 接口被扩展, 供了两个获取流的方法:

1. default Stream< E> stream() : 返回一个顺序流 
2. default Stream< E> parallelStream() : 返回一个并行流
 List<Employee> list = new ArrayList<>();
 Stream<Employee> stream = list.stream();
 Stream<Employee> parallelStream = list.parallelStream();

第二种:由数组创建流
通过 Arrays中的静态方法 stream() 创建数据源 。
static < T> Stream< T> stream(T[] array): 返回一个流

重载形式,能够处理对应基本类型的数组:

  1. public static IntStream stream(int[] array)
  2. public static LongStream stream(long[] array)
  3. public static DoubleStream stream(double[] array)
Integer[] num = new Integer[23];
Stream<Integer> stream1 = Arrays.stream(num);

第三种:由值创建流
可以使用静态方法 Stream.of(), 通过显示值 创建一个流。它可以接收任意数量的参数。
public static< T> Stream< T> of(T… values) : 返回一个流

Stream<Integer> stream2 = Stream.of(1, 5, 7);

第四种:由函数创建流,创建无限流。
可以使用静态方法 Stream.iterate() 和 Stream.generate(), 创建无限流,无限流可通过limit截断。
1. 迭代:public static< T> Stream< T> iterate(final T seed, final UnaryOperator< T> f)
2. 生成:public static< T> Stream< T> generate(Supplier< T> s)

// 迭代
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(2);
stream3.forEach(System.out::println);

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

// 生成
Stream<Double> stream4 = Stream.generate(Math::random).limit(4);
stream4.forEach(System.out::println);

执行结果

0
2
-------------
0.8009341328264229
0.3393727316726045
0.16402941830797657
0.18983964153830712

五、Stream的中间操作

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

5.1 筛选与切片

方法描述
filter(Predicate p)接收 Lambda , 从流中排除某些元素。
distinct()筛选,通过流所生成元素的 hashCode() 和 equals() 去 除重复元素
limit(long maxSize)截断流,使其元素不超过给定数量
skip(long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素 不足 n 个,则返回一个空流。不与 limit(n) 同时使用

案例:

定义一个集合: Employee 重写 hashcode , equals — 去重时使用

List<Employee> emps = Arrays.asList(
          new Employee(101, "林青霞", 28, 9889.99),
          new Employee(102, "东方不败", 29, 4329.85),
          new Employee(103, "周星驰", 40, 1233.88),
          new Employee(104, "大圣", 500, 5000.44),
          new Employee(105, "张无忌", 15, 3000.09),
          new Employee(102, "东方不败", 29, 4329.85)
  );

执行操作:

1.内部迭代 - 迭代操作由Stream API 完成操作

@Test
public void test2() {
    // 中间操作不会做任何处理
    Stream<Employee> stream = emps.stream()
            .filter((e) -> {
                System.out.println("惰性求值");
                return e.getAge() < 30;
            });
    System.out.println("--------------------");

    // 终止操作,一次性执行全部功能, 称为 "惰性求值"
    stream.forEach(System.out::println);
}

执行结果:

--------------------
惰性求值
Employee{id=101, name='林青霞', age=28, salary=9889.99, status=null}
惰性求值
Employee{id=102, name='东方不败', age=29, salary=4329.85, status=null}
惰性求值
惰性求值
惰性求值
Employee{id=105, name='张无忌', age=15, salary=3000.09, status=null}
惰性求值
Employee{id=102, name='东方不败', age=29, salary=4329.85, status=null}

2.中间操作 - 截断流

@Test
public void test4() {
     emps.stream()
             .filter(employee -> employee.getAge() < 30) // 过滤年龄小于30的人
             .limit(1) // 截取一个
             .forEach(System.out::println);
 }

执行结果:

Employee{id=101, name='林青霞', age=28, salary=9889.99, status=null}

3.中间操作 - 跳过

@Test
public void test5() {

     emps.stream()
             .filter(employee -> employee.getAge() < 30)
             .skip(2)
             .forEach(System.out::println);
 }

执行结果:

Employee{id=105, name='张无忌', age=15, salary=3000.09, status=null}
Employee{id=102, name='东方不败', age=29, salary=4329.85, status=null}

4.中间操作 - 筛选去重

@Test
public void test6() {
     emps.stream()
             .distinct()
             .forEach(System.out::println);
 }

执行结果:

Employee{id=101, name='林青霞', age=28, salary=9889.99, status=null}
Employee{id=102, name='东方不败', age=29, salary=4329.85, status=null}
Employee{id=103, name='周星驰', age=40, salary=1233.88, status=null}
Employee{id=104, name='大圣', age=500, salary=5000.44, status=null}
Employee{id=105, name='张无忌', age=15, salary=3000.09, status=null}

5.2 映射

方法描述
map(Function f)接收一个函数作为参数,该函数会被应用到每个元 素上,并将其映射成一个新的元素。
mapToDouble(ToDoubleFunction f)接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f)接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 IntStream。
mapToLong(ToLongFunction f)接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 LongStream。
flatMap(Function f)接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

1.map操作

 @Test
 public void test7() {
     List<String> list = Arrays.asList("aaa", "java", "ccc", "java8", "hello world");

     list.stream()
             .map((x) -> x.toUpperCase())
             .forEach(System.out::println);

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

     emps.stream()
             .map(Employee::getAge)
             .forEach(System.out::println);
 }

执行结果:

AAA
JAVA
CCC
JAVA8
HELLO WORLD
-------------
28
29
40
500
15
29

5.3 排序

方法描述
sorted()产生一个新流,其中按自然顺序排序
sorted(Comparator comp)产生一个新流,其中按比较器顺序排序
@Test
public void test9() {
    emps.stream()
            .map(Employee::getSalary)
            .sorted()
            .forEach(System.out::println);

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

    emps.stream()
            .map(Employee::getAge)
            .sorted(Integer::compare)
            .forEach(System.out::println);
}

执行结果:

1233.88
3000.09
4329.85
4329.85
5000.44
9889.99
-----------------
15
28
29
29
40
500

六、 Stream的终止操作

终止操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。

6.1 查找与匹配

方法描述
allMatch(Predicate p)检查是否匹配所有元素
anyMatch(Predicate p)检查是否至少匹配一个元素
noneMatch(Predicate p)检查是否没有匹配所有元素
findFirst()返回第一个元素
findAny()返回当前流中的任意元素
count()返回流中元素总数
max(Comparator c)返回流中最大值
min(Comparator c)返回流中最小值
forEach(Consumer c)内部迭代(使用 Collection 接口需要用户去做迭 代,称为外部迭代。相反,Stream API 使用内部 迭代——它帮你把迭代做了)

案例:
1.匹配

@Test
public void test10() {
    boolean allMatch = emps.stream()
            .allMatch((employee -> employee.getName().equals("林青霞")));
    System.out.println(allMatch);

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

    boolean anyMatch = emps.stream()
            .anyMatch(employee -> employee.getName().equals("林青霞"));
    System.out.println(anyMatch);

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

    boolean noneMatch = emps.stream()
            .noneMatch(employee -> employee.getName().equals("林青霞"));
    System.out.println(noneMatch);
}

执行结果:

false
-----------------
true
-----------------
false

2.第一个元素 、 任意一个元素

 @Test
public void test12() {
    Optional<String> first = emps.stream()
            .map(Employee::getName)
            .sorted()
            .findFirst(); // 获取第一个元素
    System.out.println(first.get());

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

    Optional<Employee> findAny = emps.parallelStream()
            .filter(employee -> employee.getName().equals("林青霞"))
            .findAny(); //任意一个元素
    System.out.println(findAny.get());
}

执行结果

东方不败
-----------------
Employee{id=101, name='林青霞', age=28, salary=9889.99, status=null}

3.统计总个数、 最大、 最小值

// 注意: 流一旦执行终止操作后, 就不能在重复使用
@Test
public void test13() {
    Stream<Employee> stream = emps.stream();
    long count = stream.count();
    System.out.println(count);

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

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

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

    Optional<Employee> employeeOptional = emps.stream()
            .min((x, y) -> Double.compare(x.getSalary(),  y.getSalary())); // 最小值
    System.out.println(employeeOptional.get());
}

执行结果

6
-----------------
9889.99
-----------------
Employee{id=103, name='周星驰', age=40, salary=1233.88, status=null}

6.2归约

备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它 来进行网络搜索而出名。

方法描述
reduce(T iden, BinaryOperator b)可以将流中元素反复结合起来,得到一个值。 返回 T
reduce(BinaryOperator b)可以将流中元素反复结合起来,得到一个值。 返回 Optional< T>

案例: 求和

@Test
public void test14() {
     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);
 }

执行结果

55

6.3 收集

方法描述
collect(Collector c)将流转换为其他形式。接收一个 Collector接口的 实现,用于给Stream中元素做汇总的方法
@Test
public void test16(){
   List<String> collect = emps.stream()
           .map(Employee::getName)
           .collect(Collectors.toList());
   collect.forEach(System.out::println);

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

   Set<String> set = emps.stream()
           .map(Employee::getName)
           .collect(Collectors.toSet());
   set.forEach(System.out::println);

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

   HashSet<String> hashSet = emps.stream()
           .map(Employee::getName)
           .collect(Collectors.toCollection(HashSet::new));
   hashSet.forEach(System.out::println);
}

执行结果

林青霞
东方不败
周星驰
大圣
张无忌
东方不败
-------------------
周星驰
林青霞
大圣
东方不败
张无忌
-------------------
周星驰
林青霞
大圣
东方不败
张无忌

参照:https://blog.csdn.net/liudongdong0909/article/details/77429875

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值