今天对这些内容进行了一个复习,以写demo加做笔记的形式

stream能够更加优雅的处理集合、数组等数据,让我们写出更加直观、可读性更高的数据处理代码

创建steam流的方式

set、list能够直接通过.stream()的形式创建steam流
而数组需要通过 Arrays.stream(arr); Stream.of(arr);
map需要通过entrySet()方法,先将map转换成Set<Map.Entry> set对象,再通过set.stream()的方式转换

stream中的api比较多

/** * @author Pzi * @create 2022-12-30 13:22 */@SpringBootTest@RunWith(SpringRunner.class)public class Test2 {    @Test    public void test1() {        List authors = S.getAuthors();        authors                .stream()                .distinct()                .filter(author -> {                    // 满足这个条件,那么才会被筛选到继续留在stream中                    return author.getAge()  System.out.println(author.getAge()));    }    // 对双列集合map的stream操作    @Test    public void test2() {        Map map = new HashMap();        map.put("蜡笔小新", 19);        map.put("黑子", 17);        map.put("日向翔阳", 16);        //entrySet是一个包含多个Entry的Set数据结构,Entry是key-val型的数据结构        Set<Map.Entry> entries = map.entrySet();        entries.stream()                .filter(entry -> {                    return entry.getValue() > 17;                })                .forEach(entry -> {                    System.out.println(entry);                });    }    // stream的map操作,提取stream中对象的属性,或者计算    @Test    public void test3() {        List authors = S.getAuthors();        authors                .stream()                .map(author -> author.getName())                .forEach(name -> System.out.println(name));        System.out.println(1);        authors                .stream()                .map(author -> author.getAge())                .map(age -> age + 10)                .forEach(age -> System.out.println(age));    }    // steam的sorted操作    @Test    public void test4() {        List authors = S.getAuthors();        authors                .stream()                .distinct()                .sorted(((o1, o2) -> o2.getAge() - o1.getAge()))                .skip(1)                .forEach(author -> System.out.println(author.getName() + " " + author.getAge()));    }    // flapMap的使用,重新组装,改变stream流中存放的对象    @Test    public void test5() {        //        打印所有书籍的名字。要求对重复的元素进行去重。        List authors = S.getAuthors();        authors.stream()                .flatMap(author -> author.getBooks().stream())                .distinct()                .forEach(book -> System.out.println(book.getName()));        authors.stream()                // 将以authors为对象的stream流 组装成 以book为对象的strem流                .flatMap(author -> author.getBooks().stream())                .distinct()                // 将每个book中的category转换成数组,然后将[x1,x2]代表分类的数组转换成stream流,然后使用flapMap将该数组stream流组装成以x1,x2...为对象的stream流                // 将以book为对象的strem流 组装成 以category为对象的stream流                .flatMap(book -> Arrays.stream(book.getCategory().split(",")))                .distinct()                .forEach(category -> System.out.println(category));    }    // 数组转换成stream流    @Test    public void test6() {        Integer[] arr = {1, 2, 3, 4, 5};        Stream stream = Arrays.stream(arr);        stream                .filter(integer -> integer > 3)                .forEach(integer -> System.out.println(integer));    }    @Test    public void test7() {//        打印这些作家的所出书籍的数目,注意删除重复元素。        List authors = S.getAuthors();        long count = authors                .stream()                .flatMap(author -> author.getBooks().stream())                .distinct()                .count();        System.out.println(count);    }    // max() min()    @Test    public void test8() {//分别获取这些作家的所出书籍的最高分和最低分并打印。        List authors = S.getAuthors();        Optional max = authors.stream()                .flatMap(author -> author.getBooks().stream())                .map(book -> book.getScore())                .max((score1, score2) -> score1 - score2);        Optional min = authors.stream()                .flatMap(author -> author.getBooks().stream())                .map(book -> book.getScore())                .min((score1, score2) -> score1 - score2);        System.out.println(max.get());        System.out.println(min.get());    }    // stream 的 collect()    @Test    public void test9() {        // 获取所有作者名字        List authors = S.getAuthors();        Set collect = authors.stream()                .map(author -> author.getName())                .collect(Collectors.toSet());        System.out.println(collect);        //获取一个所有书名的Set集合。        Set collect1 = authors.stream()                .flatMap(author -> author.getBooks().stream())                .map(book -> book.getName())                .collect(Collectors.toSet());        System.out.println(collect1);        //获取一个Map集合,map的key为作者名,value为List        Map<String, List> collect2 = authors.stream()                .distinct()                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));        System.out.println(collect2);    }    // anyMatch    @Test    public void test10() {        List authors = S.getAuthors();        boolean b = authors.stream()                .anyMatch(author -> author.getAge() > 29);        System.out.println(b);    }    // allMatch    @Test    public void test11() {        List authors = S.getAuthors();        boolean b = authors.stream()                .allMatch(author -> author.getAge() > 18);        System.out.println(b);    }    // findFirst    @Test    public void test12() {        List authors = S.getAuthors();        Optional first = authors.stream()                .sorted(((o1, o2) -> o1.getAge() - o2.getAge()))                .findFirst();        first.ifPresent(author -> System.out.println(author));    }    // reduce() 的使用    @Test    public void test13() {        //        使用reduce求所有作者年龄的和        List authors = S.getAuthors();        Integer sum = authors.stream()                .distinct()                .map(author -> author.getAge())                .reduce(0, (result, element) -> result + element);//                .reduce(0, (result, element) -> result + element);        System.out.println(sum);    }    @Test    public void test14() {        //        使用reduce求所有作者中年龄的最小值        List authors = S.getAuthors();        Integer minAge = authors.stream()                .map(author -> author.getAge())                .reduce(Integer.MAX_VALUE, (res, ele) -> res > ele ? ele : res);        System.out.println(minAge);    }    // 没有初始值的reduce()使用    @Test    public void test15() {        List authors = S.getAuthors();        Optional age = authors.stream()                .map(author -> author.getAge())                .reduce((res, ele) -> res > ele ? ele : res);        System.out.println(age.get());    }    // Optional对象的封装,orElseGet的使用    @Test    public void test16() {        Optional authorOptional = Optional.ofNullable(null);        Author author1 = authorOptional.orElseGet(() -> new Author(1l, "1", 1, "1", null));        System.out.println(author1);//        authorOptional.ifPresent(author -> System.out.println(author.getName()));    }    @Test    public void test17() {        Optional authorOptional = Optional.ofNullable(null);        try {            Author author = authorOptional.orElseThrow((Supplier) () -> new RuntimeException("exception"));            System.out.println(author.getName());        } catch (Throwable throwable) {            throwable.printStackTrace();        }    }    // Optional的filter()方法    // ifPresent()可以安全消费Optional中包装的对象    @Test    public void test18() {        Optional optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));        optionalAuthor                .filter(author -> author.getAge() > 14)                .ifPresent(author -> System.out.println(author));    }    // Optional的isPresent()方法,用来判断该Optional是否包装了对象    @Test    public void test19() {        Optional optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));        boolean present = optionalAuthor.isPresent();        if (present) {            System.out.println(optionalAuthor.get().getName());        }    }    //  Optional的map(),将一个 Optional 转换成另一个 Optional    @Test    public void test20() {        Optional optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));        optionalAuthor.ifPresent(author -> System.out.println(author.getBooks()));        Optional<List> books = optionalAuthor.map(author -> author.getBooks());        books.ifPresent(books1 -> System.out.println(books.get()));    }    // 类的静态方法    @Test    public void test21() {        List authors = S.getAuthors();        authors.stream()                .map(author -> author.getAge())                .map(integer -> String.valueOf(integer));        // lambda方法体中只有一行代码//                .map(String::valueOf);    }    // 对象的实例方法    @Test    public void test22() {        List authors = S.getAuthors();        Stream authorStream = authors.stream();        StringBuilder sb = new StringBuilder();        authorStream.map(author -> author.getName())                // lambda方法体中只有一行代码,且将参数全部按照顺序传入这个重写方法中                .forEach(str -> sb.append(str));    }    // 接口中只有一个抽象方法称为函数式接口    // 方法引用的条件是:lambda方法体中只有一行方法    // 构造器的方法引用    @Test    public void test23() {        List authors = S.getAuthors();        authors.stream()                .map(Author::getName)                .map(StringBuilder::new)                .map(stringBuilder -> stringBuilder.append("abc"))                .forEach(System.out::println);    }    // steam提供的处理基本数据类型,避免频繁的自动拆/装箱,从而达到省时,提高性能    @Test    public void test24() {        List authors = S.getAuthors();        authors.stream()                .map(author -> author.getAge())                .map(age -> age + 10)                .filter(age -> age > 18)                .map(age -> age + 2)                .forEach(System.out::println);        authors.stream()                .mapToInt(author -> author.getAge())                .map(age -> age + 10)                .filter(age -> age > 18)                .map(age -> age + 2)                .forEach(System.out::println);    }    @Test    public void test25() {        List authors = S.getAuthors();        authors.stream()                .parallel()                .map(author -> author.getAge())                .peek(integer -> System.out.println(integer+" "+Thread.currentThread().getName()))                .reduce(new BinaryOperator() {                    @Override                    public Integer apply(Integer result, Integer ele) {                        return result + ele;                    }                }).ifPresent(sum -> System.out.println(sum));    }}

lambda表达式

lambda表达式只关心 形参列表 和 方法体
用在重写抽象方法的时候,一般都是采用lambda表达式的方式来重写

函数式接口

函数式接口:接口中只有一个抽象方法,就称之为函数式接口。在Java中Consumer,Funciton,Supplier

方法引用

方法引用:当lambda表达式的方法体中只有一行代码,并且符合一些规则,就可以将该行代码转换成方法引用的形式
可以直接使用idea的提示自动转换
这只是一个语法糖,能看懂代码就行,不要过于纠结