Java高阶进阶之Java函数式编程-Stream流-Lambda表达式

简介

jdk1.8中新增了流Stream,和Lambda表达式
Stream流、Lambda表达式是函数式编程思想,可以让我们不用关注什么对象,而是关注对数据进行了什么操作,
Stream可以很方便对我们的集合数组进行操作。并且在大数据下处理效果高,列如有大数据量集合可以使用
我们的并行流进行操作。可以消灭嵌套地狱的if。让代码简洁、易理解,并且、快速开发。

常用操作:

常用操作(中间操作)
1. distinct():去除流中的重复元素
2. filter():对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中
3. map():对流中的元素进行计算或转换
4. sorted():对流中的元素进行排序
5. limit():可以设置流的最大长度,超出的部分将被抛弃。
6. skip():跳过流中的前n个元素,返回剩下的元素
7. flatMap():map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素
9. 常用操作:(终结操作)
10. foreach():对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
11. count();获取元素的个数
12. max&min():获取流中最大最小值
13. collect():把当前流转换一个集合
14. anyMatch():判断是否有任意符合匹配条件的元素,结果为boolean
15. allMatch():用来判断是否都符合匹配条件,结果为boolean类型
16. noneMatch():判断流中的元素是否都不符合匹配条件,结果为boolean类型
17. findAny():获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。
18. findFirst():获取流中的第一个元素。
19. parallel():将字符流转为并行流
20. peek():查看线程执行的信息

案列:

 /**
     * 打印年龄小于18,并且去重
     */
    public static void test1(List<Author> authors) {
//        List<Author> authors1 = new ArrayList<>();
        authors.stream()
                .distinct()
                .filter(author -> author.getAge() < 18)
                .forEach(author -> System.out.println("年龄小于18岁的作家为:" + author.getName()));
    }

    /**
     * 打印名字长度大于1的作家名称
     */
    public static void testAuthors() {
        Stream<Author> stream = getAuthors().stream();
        stream.filter(author -> author.getName().length() > 1)
                .forEach(author -> System.out.println(author.getName()));
    }

    /**
     * 去重,并且排序,输出年龄
     */
    public static void test5() {
        List<Author> authors = getAuthors();
//        对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
        authors.stream()
                .distinct()
                .sorted((o1, o2) -> o2.getAge() - o1.getAge())
                .forEach(author -> System.out.println(author.getAge()));
    }

    /**
     * 去重,按照年龄排序,输出前两位的作家名称
     */
    public static void test6() {
        List<Author> authors = getAuthors();
        authors.stream().distinct()
                .sorted()
                .limit(2)
                .forEach(author -> System.out.println(author.getName()));
    }

    /**
     * 打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
     */
    public static void test7() {
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted((o1, o2) -> o2.getAge() - o1.getAge())
                .skip(1)
                .forEach(author -> System.out.println(author.getName()));
    }

    /**
     * 打印所有书籍的名字。要求对重复的元素进行去重。
     */
    public static void test8() {
        List<Book> books = new ArrayList<>();
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> books.add(book));
        System.out.println(books);
    }

    /**
     * 使用map去重输出姓名
     */
    public static void test9() {
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getBooks())
                .distinct()
                .forEach(s -> System.out.println(s));
    }

    /**
     * 打印所有书籍的名字。要求对重复的书名进行去重。
     */
    public static void test10() {
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getName())
                .distinct()
                .forEach(System.out::println);

    }


    /**
     * 打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情,并获取一个list集合
     */
    public static void test11() {
        List<String> collect = getAuthors().stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .flatMap(books -> Arrays.stream(books.getCategory().split(",")))
                .distinct()
                .collect(Collectors.toList());
        System.out.println(collect);
    }

    /**
     * 分别获取这些作家的所出书籍的最高分和最低分并打印。
     */
    public static void test12() {
        List<Author> authors = getAuthors();
        Optional<Integer> max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .max((o1, o2) -> o1 - o2);
        Optional<Integer> min = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .min((o1, o2) -> o1 - o2);
        System.out.println("最大=" + max.get() + "最小=" + min.get());
    }

    /**
     * 获取一个存放所有作者名字的List集合。
     */
    public static void test13() {
        List<Author> authors = getAuthors();
        List<String> collect = authors.stream()
                .map(author -> author.getName())
                .distinct()
                .collect(Collectors.toList());
        System.out.println(collect);
    }

    /**
     * 获取一个所有书名的Set集合。
     */
    public static void test14() {
        List<Author> authors = getAuthors();
        Set<String> collect = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getName())
                .collect(Collectors.toSet());
        System.out.println(collect);
    }


    /**
     * 获取一个Map集合,map的key为作者名,value为List<Book>
     */
    public static void test15() {
        List<Author> authors = getAuthors();
        Map<String, List<Book>> collect = authors.stream()
                .distinct()
                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
    }

    /**
     * 判断是否有年龄在29以上的作家
     */
    public static void test16() {
        List<Author> authors = getAuthors();
        boolean b = authors.stream()
                .anyMatch(author -> author.getAge() > 22);
        System.out.println(b);
    }

    /**
     * 判断是否所有的作家都是成年人
     */
    public static void test17() {
        List<Author> authors = getAuthors();
        boolean b = authors.stream().allMatch(author -> author.getAge() > 11);
        System.out.println(b);
    }

    /**
     * 判断作家是否都没有超过100岁的。
     */
    public static void test18() {
        List<Author> authors = getAuthors();
        boolean b = authors.stream()
                .noneMatch(author -> author.getAge() > 10);
        System.out.println(b);
    }

    /**
     * 获取任意一个年龄大于18的作家,如果存在就输出他的名字
     */
    public static void test19() {
        List<Author> authors = getAuthors();
        Optional<Author> any = authors.stream()
                .filter(author -> author.getAge() > 18)
                .findAny();
        any.ifPresent(author -> System.out.println(author.getName()));
    }

    /**
     * 获取一个年龄最小的作家,并输出他的姓名。
     */
    public static void test20() {
        List<Author> authors = getAuthors();
        Optional<Author> first = authors.stream()
                .sorted()
                .findFirst();
        first.ifPresent(author -> System.out.println(author.getName()));
    }

    /**
     * 使用reduce求所有作者年龄的和
     */
    public static void test21() {
        List<Author> authors = getAuthors();
        Integer reduce = authors.stream()
                .distinct()
                .map(author -> author.getAge())
                .reduce(0, (result, element) -> result + element);
        System.out.println(reduce);
    }

    /**
     * 使用reduce求所有作者中年龄的最大值
     */
    public static void test22() {
        List<Author> authors = getAuthors();
        Integer reduce = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
        System.out.println(reduce);
    }

    /**
     * 使用reduce求所有作者中年龄的最小值
     */
    public static void test23() {
        List<Author> authors = getAuthors();
        Integer reduce = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
        System.out.println(reduce);
    }

    /**
     * 使用reduce求所有作者中年龄的最小值,用一个参数的重载方法去求最小值代码如下:
     */
    public static void test24() {
        List<Author> authors = getAuthors();
        Optional<Integer> reduce = authors.stream()
                .map(author -> author.getAge())
                .reduce((result, element) -> result < element ? result : element);
        reduce.ifPresent(integer -> System.out.println(integer));
    }

    /**
     * 打印作家中年龄大于17并且姓名的长度大于1的作家。并且去重
     */
    public static void test25() {
        List<Author> collect = getAuthors().stream()
                .filter(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getAge() > 14;
                    }
                }.and(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getName().length() > 1;
                    }
                }).negate()).collect(Collectors.toList());
        System.out.println(collect);
    }

    /**
     * Predicate两个参数用法
     */
    public static void test26(IntPredicate predicate, IntPredicate predicate2) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int i : arr) {
            if (predicate.and(predicate2).test(i)) {
                System.out.println(i);
            }
        }
    }

    /**
     * 打印作家中年龄大于17或者姓名的长度小于2的作家。
     */
    public static void test27() {
        getAuthors().stream()
                .filter(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getAge() > 17;
                    }
                }.or(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getName().length() < 2;
                    }
                }).negate()).distinct().forEach(author -> System.out.println(author.getName()));
    }

    /**
     * 并行流输出
     */
    private static void test() {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99);
        Integer sum = stream.parallel()
                .peek(num -> System.out.println(num + Thread.currentThread().getName()))
                .filter(num -> num > 5)
                .reduce((result, ele) -> result + ele)
                .get();
        System.out.println(sum);
    }

数据准备

private static List<Author> getAuthors() {
        //数据初始化
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
        Author author2 = new Author(2L, "亚拉索", 15, "狂风也追逐不上他的思考速度", null);
        Author author3 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);
        Author author4 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);

        //书籍列表
        List<Book> books1 = new ArrayList<>();
        List<Book> books2 = new ArrayList<>();
        List<Book> books3 = new ArrayList<>();

        Book book = new Book();
        books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));
        books1.add(new Book(2L, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何从失败中明悟真理"));

        books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(4L, "吹或不吹", "爱情,个人传记", 56, "一个哲学家的恋爱观注定很难把他所在的时代理解"));

        books3.add(new Book(5L, "你的剑就是我的剑", "爱情", 56, "无法想象一个武者能对他的伴侣这么的宽容"));
        books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
        books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));

        author.setBooks(books1);
        author2.setBooks(books2);
        author3.setBooks(books3);
        author4.setBooks(books3);

        List<Author> authorList = new ArrayList<>(Arrays.asList(author, author2, author3, author4));
        return authorList;
    }

实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author implements Comparable<Author> {
    //id
    private Long id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List<Book> books;

    @Override
    public int compareTo(Author o) {
        return this.getAge() - o.getAge();
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Book {
    //id
    private Long id;
    //书名
    private String name;

    //分类
    private String category;

    //评分
    private Integer score;

    //简介
    private String intro;

}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜡笔小心_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值