java8 - Steam

Stream

Stream(流)是一個來自數據源的元素隊列並支持聚合操作

  1. 元素是特定類型的對象,形成一個隊列。 Java中的Stream並不會存儲元素,而是按需計算。
  2. 數據源 流的來源。 可以是集合,數組,I/O channel, 產生器generator 等。
  3. 聚合操作 類似SQL語句一樣的操作, 比如filter, map, reduce, find, match, sorted等。

和以前的Collection操作不同, Stream操作還有兩個基礎的特徵:

  1. Pipelining: 中間操作都會返回流對象本身。 這樣多個操作可以串聯成一個管道, 如同流式風格(fluent style)。 這樣做可以對操作進行優化, 比如延遲執行(laziness)和短路( short-circuiting)。
  2. 內部迭代: 以前對集合遍歷都是通過Iterator或者For-Each的方式, 顯式的在集合外部進行迭代, 這叫做外部迭代。 Stream提供了內部迭代的方式, 通過訪問者模式(Visitor)實現。

Stream操作步驟如下:

  1. 創建Stream

在 Java 8 中, 集合接口有兩個方法來生成流:

stream() − 爲集合創建串行流。

parallelStream() − 爲集合創建並行流。

  1. 中間操作,如map()方法、flatMap()方法、filter()方法,返回的是符合條件的流
  2. 終止操作,allMatch()、findFirst()、count()等方法,返回的是我們需要的具體的結果

Employee類

package com.wqh.demo.java8;

public class Employee {

	private int id;
	private String name;
	private int age;
	private double salary;
	private Status status;

	public Employee() {
	}

	public Employee(String name) {
		this.name = name;
	}

	public Employee(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Employee(int id, String name, int age, double salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public Employee(int id, String name, int age, double salary, Status status) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
		this.status = status;
	}

	public Status getStatus() {
		return status;
	}

	public void setStatus(Status status) {
		this.status = status;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String show() {
		return "測試方法引用!";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		long temp;
		temp = Double.doubleToLongBits(salary);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status
				+ "]";
	}

	public enum Status {
		FREE, BUSY, VOCATION;
	}

}

創建Stream和中間操作

package com.wqh.demo.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/*
 * 一、 Stream 的操作步驟
 * 
 * 1. 創建 Stream
 * 
 * 2. 中間操作
 * 
 * 3. 終止操作
 */
public class TestStreamAPI1 {
   
   List<Employee> emps = Arrays.asList(
         new Employee(102, "李四", 59, 6666.66),
         new Employee(101, "張三", 18, 9999.99),
         new Employee(103, "王五", 28, 3333.33),
         new Employee(104, "趙六", 8, 7777.77),
         new Employee(104, "趙六", 8, 7777.77),
         new Employee(104, "趙六", 8, 7777.77),
         new Employee(105, "田七", 38, 5555.55)
   );
   
   //2. 中間操作
   /*
      映射
      map——接收 Lambda , 將元素轉換成其他形式或提取信息。接收一個函數作爲參數,該函數會被應用到每個元素上,並將其映射成一個新的元素。
      flatMap——接收一個函數作爲參數,將流中的每個值都換成另一個流,然後把所有流連接成一個流
    */
   @Test
   public void test1(){
      // map()方法返回的是隻有name的流
      Stream<String> str = emps.stream()
         .map((e) -> e.getName());

      System.out.println(str);

      System.out.println("-------------------------------------------");
      
      List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
      // map()方法返回的是每個元素都是經過大寫操作的流
      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();
   }
   
   /*
       中間操作
      sorted()——自然排序
      sorted(Comparator com)——定製排序
    */
   @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);
   }
}

終止操作來得到我們需要的結果

package com.wqh.demo.java8;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

import org.junit.Test;

import com.wqh.demo.java8.Employee.Status;

/*
 * 一、 Stream 的操作步驟
 * 
 * 1. 創建 Stream
 * 
 * 2. 中間操作
 * 
 * 3. 終止操作
 */
public class TestStreamAPI2 {
   
   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)
   );
   
   //3. 終止操作
   /*
      allMatch——檢查是否匹配所有元素
      anyMatch——檢查是否至少匹配一個元素
      noneMatch——檢查是否沒有匹配的元素
      findFirst——返回第一個元素
      findAny——返回當前流中的任意元素
      count——返回流中元素的總個數
      max——返回流中最大值
      min——返回流中最小值
    */
   @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);
   }
}
package com.wqh.demo.java8;

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.junit.Test;

import com.wqh.demo.java8.Employee.Status;

public class TestStreamAPI3 {
   
   List<Employee> emps = Arrays.asList(
         new Employee(102, "李四", 79, 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)
   );
   
   //3. 終止操作
   /*
      歸約
      reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以將流中元素反覆結合起來,得到一個值。
    */
   @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);
      
      System.out.println("----------------------------------------");
      
      Optional<Double> op = emps.stream()
         .map(Employee::getSalary)
         .reduce(Double::sum);
      
      System.out.println(op.get());
   }
   
   //需求:搜索名字中 “六” 出現的次數
   @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中元素做彙總的方法
   @Test
   public void test3(){
      List<String> list = emps.stream()
         .map(Employee::getName)
         .collect(Collectors.toList());
      
      list.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> hs = emps.stream()
         .map(Employee::getName)
         .collect(Collectors.toCollection(HashSet::new));
      
      hs.forEach(System.out::println);
   }
   
   @Test
   public void test4(){
      Optional<Double> max = emps.stream()
         .map(Employee::getSalary)
         .collect(Collectors.maxBy(Double::compare));
      
      System.out.println(max.get());
      
      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);
      
      System.out.println("--------------------------------------------");
      
      DoubleSummaryStatistics dss = emps.stream()
         .collect(Collectors.summarizingDouble(Employee::getSalary));
      
      System.out.println(dss.getMax());
   }
   
   //分組
   @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);
   }
   
   @Test
   public void test9(){
      Optional<Double> sum = emps.stream()
         .map(Employee::getSalary)
         .collect(Collectors.reducing(Double::sum));
      
      System.out.println(sum.get());
   }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章