Java8新特性(二)-强大的Stream API

一,Stream说明

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

1,流(Stream) 到底是什么呢?

是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。 ,“集合讲的是数据,流讲的是计算! ” 

注意:

①Stream 自己不会存储元素。

②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。

③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

二,Stream的操作

1,Stream操作的三个步骤:

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

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

(3)终止操作(终端操作) :一个终止操作,执行中间操作链,并产生结果

如图:

2,创建Stream的几种方式

(1)Java8 中的 Collection 接口被扩展,提供了 两个获取流的方法: 

 default Stream<E> stream() : 返回一个顺序流

 default Stream<E> parallelStream() : 返回一个并行流

(2)Java8 中的 Arrays 的静态方法 stream() 可 以获取数组流: 

 static <T> Stream<T> stream(T[] array): 返回一个流

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

 public static IntStream stream(int[] array)

 public static LongStream stream(long[] array)

 public static DoubleStream stream(double[] array)

(3)可以使用静态方法 Stream.of(), 通过显示值 创建一个流。它可以接收任意数量的参数。 

 public static<T> Stream<T> of(T... values) : 返回一个流

(4)可以使用静态方法 Stream.iterate() 和 Stream.generate(), 创建无限流。 

 迭代

public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) 

 生成

public static<T> Stream<T> generate(Supplier<T> s)

代码示例:

@Test
 public void test1(){
  //1. Collection 提供了两个方法 stream() 与 parallelStream()
  List<String> list = new ArrayList<>();
  Stream<String> stream = list.stream(); //获取一个顺序流
  Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
  
  //2. 通过 Arrays 中的 stream() 获取一个数组流
  Integer[] nums = new Integer[10];
  Stream<Integer> stream1 = Arrays.stream(nums);
  
  //3. 通过 Stream 类中静态方法 of()
  Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);
  
  //4. 创建无限流
  //迭代
  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);
 }

3,Stream的中间操作

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

(1)筛选与切片

filter——接收 Lambda , 从流中排除某些元素。

limit——截断流,使其元素不超过给定数量。 

skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补

distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

代码示例:

@Test
 public void test2(){
  //所有的中间操作不会做任何的处理
  Stream<Employee> stream = emps.stream()
   .filter((e) -> {
    System.out.println("测试中间操作");
    return e.getAge() <= 35;
   });
  
  //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
  stream.forEach(System.out::println);
 }
 
 //外部迭代
 @Test
 public void test3(){
  Iterator<Employee> it = emps.iterator();
  
  while(it.hasNext()){
   System.out.println(it.next());
  }
 }
 
 @Test
 public void test4(){
  emps.stream()
   .filter((e) -> {
    System.out.println("短路!"); // && ||
    return e.getSalary() >= 5000;
   }).limit(3)
   .forEach(System.out::println);
 }
 
 @Test
 public void test5(){
  emps.parallelStream()
   .filter((e) -> e.getSalary() >= 5000)
   .skip(2)
   .forEach(System.out::println);
 }
 
 @Test
 public void test6(){
  emps.stream()
   .distinct()
   .forEach(System.out::println);
 }

(2)映射

代码示例:

@Test
 public void test1(){
  Stream<String> str = emps.stream()
   .map((e) -> e.getName());
  
  System.out.println("-------------------------------------------");
  
  List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
  
  Stream<String> stream = strList.stream()
      .map(String::toUpperCase);
  
  stream.forEach(System.out::println);
  
  Stream<Stream<Character>> stream2 = strList.stream()
      .map(TestStreamAPI1::filterCharacter);
  
  stream2.forEach((sm) -> {
   sm.forEach(System.out::println);
  });
  
  System.out.println("---------------------------------------------");
  
  Stream<Character> stream3 = strList.stream()
      .flatMap(TestStreamAPI1::filterCharacter);
  
  stream3.forEach(System.out::println);
 }
 public static Stream<Character> filterCharacter(String str){
  List<Character> list = new ArrayList<>();
  
  for (Character ch : str.toCharArray()) {
   list.add(ch);
  }
  
  return list.stream();
 }

(3)排序

代码示例:

@Test
 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);
 }

4,Stream的终止操作

(1)查找与匹配

代码示例:

List<Employee> emps = Arrays.asList(
   new Employee(102, "李四", 59, 6666.66, Status.BUSY),
   new Employee(101, "张三", 18, 9999.99, Status.FREE),
   new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
   new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
   new Employee(104, "赵六", 8, 7777.77, Status.FREE),
   new Employee(104, "赵六", 8, 7777.77, Status.FREE),
   new Employee(105, "田七", 38, 5555.55, Status.BUSY)
 );
 
 @Test
 public void test1(){
   boolean bl = emps.stream()
    .allMatch((e) -> e.getStatus().equals(Status.BUSY));
   
   System.out.println(bl);
   
   boolean bl1 = emps.stream()
    .anyMatch((e) -> e.getStatus().equals(Status.BUSY));
   
   System.out.println(bl1);
   
   boolean bl2 = emps.stream()
    .noneMatch((e) -> e.getStatus().equals(Status.BUSY));
   
   System.out.println(bl2);
 }
 
 @Test
 public void test2(){
  Optional<Employee> op = emps.stream()
   .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
   .findFirst();
  
  System.out.println(op.get());
  
  System.out.println("--------------------------------");
  
  Optional<Employee> op2 = emps.parallelStream()
   .filter((e) -> e.getStatus().equals(Status.FREE))
   .findAny();
  
  System.out.println(op2.get());
 }
 
 @Test
 public void test3(){
  long count = emps.stream()
       .filter((e) -> e.getStatus().equals(Status.FREE))
       .count();
  
  System.out.println(count);
  
  Optional<Double> op = emps.stream()
   .map(Employee::getSalary)
   .max(Double::compare);
  
  System.out.println(op.get());
  
  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);
 }

猜你喜欢

转载自blog.csdn.net/hhq12/article/details/81169145