java8中一個極其強悍的新特性Stream(非常實用)

本博客系轉載:https://zhuanlan.zhihu.com/p/97493325

1.Stream語法講解

Stream執行流程很簡單,主要有三個,首先創建一個Stream,然後使用Stream操作數據,最後終止Stream。有點類似於Stream的生命週期。下面我們根據其流程來一個一個講解。
前提準備,首先我們創建一個Student類,以後我們每次都是操作這個類。

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private Double score;
    public Student() {
    }
    public Student(Integer id, String name, Integer age, Double score) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
    }
    //getter和setter方法
    //toString方法
}

2.創建一個Stream

2.1.通過一個集合創建Stream

@Test
public void test1(){
    List<Student> studentList = StudentData.getStudents();
    //第一種:返回一個順序流
    Stream<Student> stream = studentList.stream();
    //第二種:返回一個並行流
    Stream<Student> stream2 = studentList.parallelStream();
}

2.2.通過一個數組創建Stream

    @Test
    public void test2(){
        //獲取一個整形Stream
        int[] arr = new int[]{1,2,34,4,65,7,87,};
        IntStream intStream = Arrays.stream(arr);
        //獲取一個Student對象Stream
        Student[] students = StudentData.getArrStudents();
        Stream<Student> stream = Arrays.stream(students);
    }

2.3.通過Stream.of

    @Test
    public void test3(){
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 5, 6, 7, 8);
        Stream<String> stringStream = Stream.of("1", "2", "3", "4", "5");
        Stream<Student> studentStream = Stream.of(
                new Student(1, "劉備", 18, 90.4),
                new Student(2, "張飛", 19, 87.4),
                new Student(3, "關羽", 21, 67.4));
    }

2.4.創建一個無限流

@Test
public void test4(){
    //每隔5個數取一個,從0開始,此時就會無限循環
    Stream.iterate(0,t->t+5).forEach(System.out::println);
    //每隔5個數取一個,從0開始,只取前5個數
    Stream.iterate(0,t->t+5).limit(5).forEach(System.out::println);
    //取出一個隨機數
    Stream.generate(Math::random).limit(5).forEach(System.out::println);
}

3.使用Stream操作數據

3.1.篩選和切片

@Test
public void test1(){
    List<Student> list  = StudentData.getStudents();
    //(1)過濾:過濾出所有年齡大於20歲的同學
    list.stream().filter(item->item.getAge()>20).forEach(System.out::println);
    //(2)截斷流:篩選出前3條數據
    list.stream().limit(3).forEach(System.out::println);
    //(3)跳過元素:跳過前5個元素
    list.stream().skip(5).forEach(System.out::println);
    //(4)過濾重複數據:
    list.stream().distinct().forEach(System.out::println);
}

3.2.映射

@Test
public  void test2(){
    //(1)map操作
    List<String> list  = Arrays.asList("java","python","go");
    Stream<String> stream = list.stream();
    //此時每一個小寫字母都有一個大寫的映射
    stream.map(str -> str.toUpperCase()).forEach(System.out::println);
    //篩選出所有的年齡,再過濾出所有大於20的年齡有哪些
    List<Student> studentList  = StudentData.getStudents();
    Stream<Student> stream1 = studentList.stream();
    Stream<Integer> ageStream = stream1.map(Student::getAge);
    ageStream.filter(age->age>20).forEach(System.out::println);
    //(2)floatMap:將流中的每一個值換成另外一個流
}

3.3.排序

public  void test3(){
    //(1)自然排序
    List<Integer> list  = Arrays.asList(4,3,7,9,12,8,10,23,2);
    Stream<Integer> stream = list.stream();
    stream.sorted().forEach(System.out::println);
    //(2)對象排序:對象類可以先實現comparable接口,或者是直接指定
    //第一種:先實現compable接口
    List<Student> studentList  = StudentData.getStudents();
    studentList.stream().sorted().forEach(System.out::println);
    //第二種:直接指定comparable
    List<Student> studentList1  = StudentData.getStudents();
    studentList1.stream()
            .sorted((e1,e2)-> Integer.compare(e1.getAge(),e2.getAge()))
            .forEach(System.out::println);
}

4.終止Stream

4.1.匹配和查找

public void test1(){
    List<Student> list  = StudentData.getStudents();
    //(1)判斷所有的學生年齡是否都大於20歲
    boolean allMatch = list.stream().allMatch(item -> item.getAge() > 20);
    //(2)判斷是否存在學生的年齡大於20歲
    boolean anyMatch = list.stream().anyMatch(item -> item.getAge() > 20);
    //(3)判斷是否存在學生叫曹操
    boolean noneMatch = list.stream().noneMatch(item -> item.getName().equals("曹操"));
    //(4)查找第一個學生
    Optional<Student> first = list.stream().findFirst();
    //(5)查找所有的學生數量
    long count = list.stream().count();
    long count1 = list.stream().filter(item -> item.getScore() > 90.0).count();
    //(6)查找當前流中的元素
    Optional<Student> any = list.stream().findAny();
    //(7)查找學生最高的分數:Student實現了comparable接口的話,可直接比較
    Stream<Double> doubleStream = list.stream().map(item -> item.getScore());
    doubleStream.max(Double::compare);
    //(8)查找學生最低的分數
}

4.2.歸約

public void test2(){
    //(1)計算數的總和
    List<Integer> list = Arrays.asList(1,2,3,4,5);
    list.stream().reduce(0,Integer::sum);
    //(3)計算學生總分
    List<Student> studentList = StudentData.getStudents();
    Stream<Double> doubleStream = studentList.stream().map(Student::getScore);
    doubleStream.reduce(Double::sum);
}

4.3.收集

public void test3(){
    List<Student> studentList = StudentData.getStudents();
    //返回一個list
    List<Student> listStream = studentList.stream()
            .filter(e -> e.getAge() > 18)
            .collect(Collectors.toList());
    //返回一個Set
    Set<Student> setStream = studentList.stream()
            .filter(e -> e.getAge() > 18)
            .collect(Collectors.toSet());
    //返回其他的類型
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章