Java8新特性之Stream API詳解

一、前言

StreamAPI在Java8版本中使用,關註的是對數據的篩選、查找、存儲等

它可以做的事情有:過濾、排序、映射、歸約

二、使用流程

Stream實例化中間操作(過濾、排序、映射、規約)終止操作(匹配查找、歸約、收集)

三、案例演示

public class EmployeeData {
   
   public static List<Employee> getEmployees(){
      List<Employee> list = new ArrayList<>();
      
      list.add(new Employee(1001, "馬化騰", 34, 6000.38));
      list.add(new Employee(1002, "馬雲", 12, 9876.12));
      list.add(new Employee(1003, "劉強東", 33, 3000.82));
      list.add(new Employee(1004, "雷軍", 26, 7657.37));
      list.add(new Employee(1005, "李彥宏", 65, 5555.32));
      list.add(new Employee(1006, "比爾蓋茨", 42, 9500.43));
      list.add(new Employee(1007, "任正非", 26, 4333.32));
      list.add(new Employee(1008, "紮克伯格", 35, 2500.32));
      
      return list;
   }
   
}
package JDK_8;

import org.junit.Test;

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

public class StreamAPI {
    // 方式1:使用集合創建Stream
    @Test
    public void test1() {
        List<Employee> list = EmployeeData.getEmployees();
        // 返回一個順序流
        Stream<Employee> stream = list.stream();
        // 返回一個並行流
        Stream<Employee> employeeStream = list.parallelStream();
    }

    // 方式2:使用數組創建流對象
    @Test
    public void test2() {
        Employee e1 = new Employee(1003, "WZY", 26, 3000.69);
        Employee e2 = new Employee(1007, "王紫玉", 25, 8888);

        Employee[] list2 = new Employee[]{e1, e2};
        Stream<Employee> stream = Arrays.stream(list2);
        stream.forEach(System.out::println);

    }

    // 通過Stream.of 創建
    @Test
    public void test3() {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
        stream.forEach(System.out::println);
    }

    // Stream.filter進行過濾
    @Test
    public void test4() {
        List<Employee> list = EmployeeData.getEmployees();
        list.stream().filter(employee -> employee.getAge() > 25).forEach(System.out::println);
    }

    // 使用StreamAPI篩選
    @Test
    public void test5() {
        List<Employee> list = EmployeeData.getEmployees();
        list.add(new Employee(1004, "wzy", 25, 18888));
        list.add(new Employee(1004, "wzy", 25, 18888));
        list.add(new Employee(1004, "wzy", 25, 18888));
        list.add(new Employee(1004, "wzy", 25, 18888));

        list.stream().forEach(System.out::println);
        System.out.println();
        list.stream().distinct().forEach(System.out::println);
    }

    @Test
    public void test6() {
        List<String> list = Arrays.asList("a", "b", "c");
//        map(Function<? super T,? extends R> mapper)
//        返回由給定函數應用於此流的元素的結果組成的流。
        list.stream().map(s -> s.toUpperCase()).forEach(System.out::println);

    }

    // 使用StreamAPI篩選:工資大於6000的員工
    @Test
    public void test7() {
        List<Employee> list = EmployeeData.getEmployees();
        list.stream().filter(s -> s.getSalary() > 6000).forEach(System.out::println);
    }

    // StreamAPI映射:map,接收參數,將參數轉換為其他形式的信息;
    @Test
    public void test8() {
        List<Employee> list = EmployeeData.getEmployees();
        list.stream().map(e -> e.getAge()).forEach(System.out::println);

    }

    // StreamAPI排序,sorted幫助實現Comparable接口進行對象比較
    @Test
    public void test9() {
        List<Employee> list = EmployeeData.getEmployees();
        list.stream().sorted((e1, e2) -> {
            int ageValue = Integer.compare(e1.getAge(), e2.getAge());
            if (ageValue != 0) {
                return ageValue;
            } else {
                return Double.compare(e1.getSalary(), e2.getSalary());
            }
        }).forEach(System.out::println);
    }

    // StreamAPI匹配:所有元素是否滿足下列條件
    @Test
    public void test10() {
        List<Employee> list = EmployeeData.getEmployees();
        boolean allMatch = list.stream().allMatch(e -> e.getSalary() > 5000);
        System.out.println(allMatch);
    }

    // StreamAPI查找:返回第一個元素
    @Test
    public void test11() {
        List<Employee> list = EmployeeData.getEmployees();
        Optional<Employee> first = list.stream().findFirst();
        System.out.println(first);
    }

    // StreamAPI查找:返回薪水數最大的員工
    @Test
    public void test12() {
        List<Employee> list = EmployeeData.getEmployees();
        Stream<Double> salaryStream = list.stream().map(e -> e.getSalary());
        Optional<Double> max = salaryStream.max(Double::compare);
        System.out.println(max);
    }

    // StreamAPI查找:薪水最小的員工對像
    @Test
    public void test13() {
        List<Employee> list = EmployeeData.getEmployees();
        Optional<Employee> min = list.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(min);
    }

    // StreamAPI:歸約
    @Test
    public void test14() {
        List<Employee> list = EmployeeData.getEmployees();
        Stream<Double> salaryStream = list.stream().map(e -> e.getSalary());
        Optional<Double> sum = salaryStream.reduce((s1, s2) -> s1 + s2);
        System.out.println(sum.get());
    }

    // StreamAPI:收集
    @Test
    public void test15(){
        List<Employee> list = EmployeeData.getEmployees();
        List<Employee> employeeList = list.stream().filter(e -> e.getSalary() > 5000).collect(Collectors.toList());
        for (Employee employee : employeeList) {
            System.out.println(employee);
        }
    }
}

到此這篇關於Java8新特性之StreamAPI詳解的文章就介紹到這瞭,更多相關java StreamAPI詳解內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: