stream(流的使用)

/**
* 創建流
*
1.of() 由Stream的靜態方法of()創建: Stream stream = Stream.of(“Lambda”, “Java8”, “JavaWeb”, “javaEE”);
* 2.由數組創建流 由Arrays的靜態方法stream()創建 String[] words = {“Hello”, “World”}; Arrays.stream(words)
* 3.由文件生成流 通過Files的lines()方法,會將每一行都轉化稱爲stream
* 4.由函數生成流:創建無限流(流沒有結尾)
*
* 使用流
*
* 一.篩選和切片
1.篩選(filter方法) 即我們之前的過濾,參數是一個謂詞Predicate,
並且返回所有複合謂詞判斷的元素的流
2.去重 distinct()
3.截短流 limit()
4.跳過元素 skip()

  • 二.映射()
    1.map() 它會接受一個函數作爲參數。這個函數會被應用到每個元素上,並將其映射成一個新的元素
    2.floatMap() 把流中的每個值都轉換成另一個流,然後把所有的流連接起來稱爲一個流

    *三.查找與匹配

    • 查看數據集中的某些元素是否匹配一個給定的屬性

    • 主要有以下幾個API: allMatch、anyMatch、noneMatch、findFirst和findAny
      1.allMatch 檢查是否匹配所有元素
      2.anyMatch 檢查至少匹配一個元素
      3.noneMathch 代表流中沒有任何元素與給定的條件匹配
      4.findFirst 查找第一個元素
      Optional findFirst()返回描述此流的第一個元素的Optional如果流爲空,
      則返回一個空的Optional 。
      如果流沒有遇到順序,則可能會返回任何元素。
      5.findAny 將返回當前流中的任意元素,隨機

    • 四.歸約
      1.元素求和 reduce
      2.最大和最小 max() and min()

- 案例

package IO.stream;
import org.junit.Before;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * User: 彭家琪
 * Date: 2019/9/16   15:19
 */
public class StreamDemo {

    private List<java8.Employee> employees = new ArrayList<>(6);

    @Before
    public void before() {

        employees.add(new Employee(0001, "張三", 26, 6500, 822));
        employees.add(new Employee(0002, "李四", 29, 8500, 881));
        employees.add(new Employee(0003, "王五", 24, 3500, 839));
        employees.add(new Employee(0004, "趙六", 32, 11300, 803));
        employees.add(new Employee(0005, "胡七", 32, 13100, 946));
        employees.add(new Employee(0006, "劉八", 28, 7500, 866`在這裏插入代碼片`));
    }

 

    /**
     * 創建流
     *
     *      1.of()  由Stream的靜態方法of()創建: Stream<String> stream = Stream.of("Lambda", "Java8", "JavaWeb", "javaEE");
     *      2.由數組創建流    由Arrays的靜態方法stream()創建    String[] words = {"Hello", "World"};    Arrays.stream(words)
     *      3.由文件生成流   通過Files的lines()方法,會將每一行都轉化稱爲stream
     *      4.由函數生成流:創建無限流(流沒有結尾)
     *
     * 使用流
     *
     * 一.篩選和切片
            1.篩選(filter方法) 即我們之前的過濾,參數是一個謂詞Predicate,
                並且返回所有複合謂詞判斷的元素的流
                例如: 上述簡單案例,篩選出年齡小於30的員工
            2.去重 distinct()
            3.截短流 limit()
            4.跳過元素 skip()

     * 二.映射()
            1.map() 它會接受一個函數作爲參數。這個函數會被應用到每個元素上,並將其映射成一個新的元素
            2.floatMap()  把流中的每個值都轉換成另一個流,然後把所有的流連接起來稱爲一個流


     *三.查找與匹配
     *     查看數據集中的某些元素是否匹配一個給定的屬性
     *     主要有以下幾個API: allMatch、anyMatch、noneMatch、findFirst和findAny
            1.allMatch 檢查是否匹配所有元素
            2.anyMatch 檢查至少匹配一個元素
            3.noneMathch  代表流中沒有任何元素與給定的條件匹配
            4.findFirst 查找第一個元素
                 Optional<T> findFirst()返回描述此流的第一個元素的Optional如果流爲空,
                 則返回一個空的Optional 。
                 如果流沒有遇到順序,則可能會返回任何元素。
            5.findAny 將返回當前流中的任意元素,隨機


     * 四.歸約
            1.元素求和 reduce
            2.最大和最小 max() and  min()



     */

    //去重
    @Test
    private void test2() {
        List<Integer> num = Arrays.asList(1, 2, 3, 2, 4, 2, 4, 5);
        num.stream().filter(i -> i % 2 != 0).distinct().forEach(System.out::println);
    }
    //映射
    @Test
    public void maptest3() {
        List<String> result = employees.stream().map(employee -> employee.getName()).collect(Collectors.toList());
        System.out.println(result);

        //1.映射稱爲新的集合,集合內容爲原集合元素的字符串長度
        //2.映射稱爲新的集合,集合內容爲原集合元素的字符串的大寫

        List<String> lis = Arrays.asList("Lambda", "java8", "javaWeb","javaEE");
        lis.stream().map(e->e.length()).collect(Collectors.toList()).forEach(System.out::println);//1
        lis.stream().map(e->e.toUpperCase()).collect(Collectors.toList()).forEach(System.out::println);//2
    }
    @Test
    public void findtest4() {
        System.out.println(employees.stream().allMatch(employee -> employee.getAge() < 30 && employee.getAge() > 25));

        System.out.println(employees.stream().anyMatch(employee -> employee.getAge() < 30));

        System.out.println(employees.stream().noneMatch(employee -> employee.getAge() > 30));

        Optional<java8.Employee> first = employees.stream().filter(employee -> employee.getAge() < 30).findFirst();
        System.out.println(first);


    }


    @Test
    public void gytest5() {
        List<Integer> i = Arrays.asList(1,3,5,7,9,11,13,15,17,19,21);
        System.out.println(i.stream().reduce(0, (x, y) -> x + y));

        Optional<Double> sum = employees.stream().map(employee -> employee.getSalary()).reduce((a, b) -> a + b);
        System.out.println("sum: "+sum);
        //  System.out.println(employees.stream().map(employee -> employee.getSalary()).reduce(Double::sum ));

        Integer max = i.stream().reduce(0,(a, b) -> a > b ?  a : b );
        System.out.println("最高: "+max);

  // employees.stream().sorted((e1,e2)->e1.getAge() - e2.getAge()).forEach(System.out::println);
   employees.stream().sorted(Comparator.comparingInt(java8.Employee::getAge)).forEach(System.out::println);

    }

    @Test
    public void random(){
        Stream.generate(Math::random) .limit(5) .forEach(System.out::println);
    }


}

package java8;

/**
 * User: 彭家琪
 * Date: 2019/9/11   11:33
 */
public class Employee {

    private int id;
    private String name;
    private int age;
    private double salary;
    private int workHoursForYears;

    public Employee() {

    }



    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 +
                ", workHoursForYears=" + workHoursForYears +
                '}';
    }

    public int getId() {
        return id;
    }

    public int getWorkHoursForYears() {
        return workHoursForYears;
    }

    public void setWorkHoursForYears(int workHoursForYears) {
        this.workHoursForYears = workHoursForYears;
    }

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

在這裏插入圖片描述

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