import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.junit.Test; /* * 1、 Stream 的操做步驟 * * 1. 建立 Stream * 2. 中間操做 * 3. 終止操做 */ public class TestStreamAPI1 { /** * 建立 Stream */ @Test public void test1(){ //1. Collection 提供了兩個方法 stream() 與 parallelStream() List<String> list = new ArrayList<>(); Stream<String> stream = list.stream(); // 獲取一個順序流 Stream<String> pstream = 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); stream3.limit(3).forEach(System.out::println); //生成 Stream<Double> stream4 = Stream.generate(Math::random); stream4.limit(3).forEach(System.out::println); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.junit.Test; /** * 中間操做 */ public class TestStreamAPI2 { /** * 篩選與切片 * filter 從通道流中按自定義的規則過濾出知足條件的序列 * limit 截斷流,使流中元素不超過指定數量 * skip 跳過流中指定個數的序列 * distinct 去除流中重複元素 */ @Test public void test1(){ List<Integer> list = Arrays.asList(2, 3, 5, 5, 5, 8, 11, 15); System.out.println("--------------------------filter"); // 全部的中間操做不會作任何的處理 Stream<Integer> stream = list.stream() .filter((i) -> { System.out.println("測試中間操做"); return i > 5; }); // 只有當作終止操做時,全部的中間操做會一次性的所有執行,稱爲「惰性求值」 stream.forEach(System.out::println); System.out.println("--------------------------limit"); list.stream() .filter((i) -> { System.out.println("短路!"); // && || return i > 5; }).limit(1) .forEach(System.out::println); System.out.println("--------------------------skip"); list.stream() .filter((i) -> i > 5) .skip(2) .forEach(System.out::println); System.out.println("--------------------------distinct"); list.stream() .distinct() .forEach(System.out::println); } /** * 映射 * map 接收一個函數做爲參數,該函數會被應用到每一個元素上,並將其映射成一個新的元素。 * flatMap 接收一個函數做爲參數,將流中的每一個值都換成另外一個流,而後把全部流鏈接成一個流 */ @Test public void test2() { List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"); System.out.println("--------------------------map"); Stream<String> stream1 = strList.stream() .map(String::toUpperCase); stream1.forEach(System.out::println); System.out.println("--------------------------flatMap"); // map方式 Stream<Stream<Character>> stream2 = strList.stream() .map(TestStreamAPI2::filterCharacter); stream2.forEach((sm) -> { sm.forEach(System.out::println); }); // flatMap方式 Stream<Character> stream3 = strList.stream() .flatMap(TestStreamAPI2::filterCharacter); stream3.forEach(System.out::println); } private static Stream<Character> filterCharacter(String str){ List<Character> list = new ArrayList<>(); for (Character ch : str.toCharArray()) { list.add(ch); } return list.stream(); } /** * 排序 * sorted() 天然排序(Comparable) * sorted(Comparator com) 定製排序(Comparator) */ @Test public void Test3() { List<Character> strList = Arrays.asList('C', 'E', 'A', 'D', 'G', 'F', 'B'); System.out.println("--------------------------sorted天然排序"); strList.stream() .sorted() //.sorted(Collections.reverseOrder()) .forEach(System.out::println); System.out.println("--------------------------sorted定製排序"); strList.stream() .sorted((x, y) -> { if('D' <= x || 'D' <= y){ return x.compareTo(y); }else if('D' >= x || 'D' >= y){ return -Integer.compare(x, y); } return 0; }).forEach(System.out::println); } }
public class Employee { private int id; private String name; private int age; private double salary; private Status status; public Employee() { } 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; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status + "]"; } public enum Status { FREE, BUSY, VOCATION; } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.DoubleSummaryStatistics; 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.example.demo.stream.Employee.Status; /** * 終止操做 */ public class TestStreamAPI3 { 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) ); /** * 查找與匹配 * allMatch 檢查是否匹配全部元素 * anyMatch 檢查是否至少匹配一個元素 * noneMatch 檢查是否沒有匹配的元素 * findFirst 返回第一個元素 * findAny 返回當前流中的任意元素 * count 返回流中元素的總個數 * max 返回流中最大值 * min 返回流中最小值 */ @Test public void test1() { System.out.println("--------------------------allMatch"); boolean b1 = emps.stream() .allMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(b1); System.out.println("--------------------------anyMatch"); boolean b2 = emps.stream() .anyMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(b2); System.out.println("--------------------------noneMatch"); boolean b3 = emps.stream() .noneMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(b3); System.out.println("--------------------------findFirst"); Optional<Employee> op1 = emps.stream() .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())) .findFirst(); System.out.println(op1.get()); System.out.println("--------------------------findAny"); Optional<Employee> op2 = emps.parallelStream() .filter((e) -> e.getStatus().equals(Status.FREE)) .findAny(); System.out.println(op2.get()); System.out.println("--------------------------count"); long count = emps.stream() .filter((e) -> e.getStatus().equals(Status.FREE)) .count(); System.out.println(count); System.out.println("--------------------------max"); Optional<Double> op3 = emps.stream() .map(Employee::getSalary) .max(Double::compare); System.out.println(op3.get()); System.out.println("--------------------------min"); Optional<Employee> op4 = emps.stream() .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(op4.get()); } /** * 歸約 * reduce(T identity, BinaryOperator) 能夠將流中元素反覆結合起來,獲得一個值,返回 T * reduce(BinaryOperator) 能夠將流中元素反覆結合起來,獲得一個值,返回 Optional<T> */ @Test public void test2() { 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<Integer> op = list.stream() .reduce(Integer::sum); System.out.println(op.get()); } /** * 收集 * collect 將流轉換爲其餘形式,接收一個Collector接口的實現,用於給Stream中元素作彙總方法 * * Collectors類方法 * toList List<T> 把流中元素收集到List * toSet Set<T> 把流中元素收集到Set * toCollection Collection<T> 把流中元素收集到建立的集合 */ @Test public void test3() { System.out.println("--------------------------list"); List<String> list = emps.stream() .map(Employee::getName) .collect(Collectors.toList()); list.forEach(System.out::println); System.out.println("--------------------------set"); Set<String> set = emps.stream() .map(Employee::getName) .collect(Collectors.toSet()); set.forEach(System.out::println); System.out.println("--------------------------collection"); Collection<String> collection = emps.stream() .map(Employee::getName) .collect(Collectors.toCollection(ArrayList::new)); collection.forEach(System.out::println); } /** * Collectors類方法 * counting Long 計算流中元素的個數 * summingInt Integer 對流中項目的一個整數屬性求和 * averagingInt Double 計算流中項目 Integer 屬性的平均值 * maxBy Optional<T> 根據比較器選擇最大值 * minBy Optional<T> 根據比較器選擇最小值 * summarizingInt IntSummaryStatistics 收集關於流中項目 Integer 屬性的統計值,例如最大、最小、總和與平均值 */ @Test public void test4() { System.out.println("--------------------------count"); Long count = emps.stream() .collect(Collectors.counting()); System.out.println(count); System.out.println("--------------------------sum"); Double sum = emps.stream() .collect((Collectors.summingDouble(Employee::getSalary))); System.out.println(sum); System.out.println("--------------------------avg"); Double avg = emps.stream() .collect((Collectors.averagingDouble(Employee::getSalary))); System.out.println(avg); System.out.println("--------------------------max"); Optional<Employee> max = emps.stream() .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(),e2.getSalary()))); System.out.println(max); System.out.println("--------------------------mix"); Optional<Double> mix = emps.stream() .map(Employee::getSalary) .collect(Collectors.minBy(Double::compare)); System.out.println(mix.get()); System.out.println("--------------------------statistics"); DoubleSummaryStatistics dss = emps.stream() .collect(Collectors.summarizingDouble(Employee::getSalary)); System.out.println(dss.getMax() + "--" + dss.getMin() + "--" + dss.getCount()); } /** * Collectors類方法 * joining String 鏈接流中每一個字符串 */ @Test public void test5() { System.out.println("--------------------------join"); String join = emps.stream() .map(Employee::getName) .collect(Collectors.joining("," , "----", "----")); System.out.println(join); } /** * Collectors類方法 * groupingBy Map<K, List<T>> 根據某屬性值對流分組,屬性爲K,結果爲V */ @Test public void test6() { System.out.println("--------------------------group"); Map<Status, List<Employee>> group = emps.stream() .collect(Collectors.groupingBy(Employee::getStatus)); System.out.println(group); System.out.println("--------------------------multistage group"); Map<Status, Map<String, List<Employee>>> mgroup = 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(mgroup); } /** * Collectors類方法 * partitioningBy Map<Boolean, List<T>> 根據true或false進行分區 */ @Test public void test7() { System.out.println("--------------------------partition"); Map<Boolean, List<Employee>> partition = emps.stream() .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000)); System.out.println(partition); } }