java8函数式编程

package com.example.Functional.Stream;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo {

    //==================================

    /**
     * 打印所有年龄小于18的作家的名字,去重
     */
    public static void main(String[] args) {
//        test01(authors);
//        test02(authors);//演示使用数组创建流
//        test03(authors);//使用map创建流
//        test04(authors);
//        test05();//map方法
//        test06();//distinct方法
//        test07();//sorted
//        test08();//limit
//        test09();//skip
//        test10();//flatMap例子1
//        test11();//flatMap例子2,flatMap+Arrays.stream()
//        test12();//foreach---终结操作
//        test13();//count方法---终结操作
//        test14();//max&min---终结操作
//        test15();//collect---终结操作--Collectors.toList()
//        test116();//collect---中介操作---Collectors.toSet()
//        test17();//collect---中介操作---Collectors.toMap
//        test18();//终结操作之查找与匹配---anyMatch
//        test19();//终结操作之查找与匹配---allMatch
//        test20();//终结操作之查找与匹配---NoneMatch
        test21();//终结操作之查找与匹配---findAny
        test22();//终结操作之查找与匹配---findFirst


    }

    //findFirst:获取流中的第一个元素
    private static void test22() {
        //获取一个年龄最小的作家,并输出他的姓名。
        Optional<Author> optionalAuthor = getAuthors().stream()
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .findFirst();

        optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
    }

    //findAny:获取流中任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素
    private static void test21() {
        //获取任意一个年龄大于18岁的作家,如果存在就输出他的名字
        Optional<Author> optionalAuthor = getAuthors().stream()
                .filter(author -> author.getAge() > 18)
                .findAny();
        optionalAuthor.ifPresent(new Consumer<Author>() {
            @Override
            public void accept(Author author) {
                System.out.println(author.getName());
            }
        });
    }

    //noneMatch:可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false
    private static void test20() {
        //判断作家是否都没有超过200岁
        boolean b = getAuthors().stream()
                .noneMatch(author -> author.getAge() > 200);
        System.out.println(b);

    }

    //allMatch:可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为ture,否则结果为false。
    private static void test19() {
        //判断是否所有的作家都是成年人
        boolean b = getAuthors().stream()
                .allMatch(author -> author.getAge() >= 18);
        System.out.println(b);
    }

    //anyMatch:可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型
    private static void test18() {
        //判断是否有年龄在29岁之上的作家
        boolean b = getAuthors().stream()
                .anyMatch(author -> author.getAge() > 29);
        System.out.println(b);
    }

    private static void test17() {
        //获取一个map集合,map的key为作者名,value为List<Book>
        Map<String, List<Book>> map = getAuthors().stream()
                .distinct()
                .collect(Collectors.toMap(Author::getName, Author::getBooks));

        System.out.println(map);
    }

    private static void test116() {
        //获取一个所有书名的Set集合
        Set<String> set = getAuthors().stream()
                .map(Author::getName)
                .collect(Collectors.toSet());


        System.out.println(set);
    }

    //把当前流转换成一个集合
    private static void test15() {
        //获取一个存放所有作者名字的List集合
        List<String> list = getAuthors().stream()
                .map(Author::getName)
                .collect(Collectors.toList());
        System.out.println(list);
    }

    //可以用来取流中的最值
    private static void test14() {
        //分别获取
        List<Author> authors = getAuthors();
        Optional<Integer> max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .flatMap(book -> Stream.of(book.getScore()))
                .max((o1, o2) -> o1 - o2);
//                .min((o1, o2) -> o1.getScore() - o2.getScore());
        System.out.println(max.get());


    }

    //可以用来获取流当中元素的个数
    private static void test13() {
        //打印作家所出书籍数目,注意删除重复元素
        List<Author> authors = getAuthors();
        long count = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .count();
        System.out.println(count);


    }

    //对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么操作
    private static void test12() {
        //输出作家的名字
        List<Author> authors = getAuthors();
        authors.stream()
                .map(Author::getName)
                .distinct()
                .forEach(System.out::println);

    }

    private static void test11() {
        //打印现有书籍的所有分类,要求对分类进行去重,不能出现这种格式:哲学,爱情
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
                .distinct()
                .forEach(System.out::println);
    }

    //flatMap,map只能把一个对象转换成另一个对象来作为流中的元素,而flatMap可以把一个对象转换成多个对象作为流的元素
    private static void test10() {
        //打印所有书籍的名字,要求对重复的元素进行去重
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> System.out.println(book.getCategory()));
    }

    //skip,跳过流中的前n个元素,返回剩下的元素
    private static void test09() {
        //打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
                .skip(1)
                .forEach(System.out::println);
    }

    //limit可以设置流的最大长度,超出的部分将被抛弃
    private static void test08() {
        //对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
                .limit(2)
                .forEach(System.out::println);
    }

    //sorted,可以对流中的元素进行排序
    private static void test07() {
        //对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted((o1, o2) -> o2.getAge() - o1.getAge())
                .forEach(System.out::println);

    }

    //distinct,去除流中重复的元素
    //注意:distinct方法是依赖Object的equals方法来判断是否是相同的度效果,所以要重写equals方法
    //lombok 的@Data注解包含了@EqualsAndHashCode注解
    private static void test06() {
        //打印所有作家名称吗,并且要求名称不能重复
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .forEach(author -> System.out.println(author.getName()));

    }

    //map,可以把流中的元素进行计算或转换
    private static void test05() {
        List<Author> authors = getAuthors();
        /*authors.stream()
                .map(Author::getName)
                .forEach(System.out::println);*/
        authors.stream()
                .map(author -> author.getName() + "嘿嘿嘿")
                .forEach(System.out::println);

    }

    //打印所有姓名长度大于1的作家的姓名
    private static void test04(List<Author> authors) {
        authors.stream()
                .filter(author -> author.getName().length() > 1)
                .forEach(author -> System.out.println(author.getName()));

    }

    //使用map创建流
    private static void test03(List<Author> authors) {
        Map<String, Integer> map = new HashMap<>();
        map.put("蜡笔小新", 19);
        map.put("小黑子", 17);
        map.put("向日葵", 16);

        map.entrySet().stream()
                .filter(entry -> entry.getValue() > 16)
                .forEach(System.out::println);
    }

    /**
     * 演示使用数组创建流
     */
    private static void test02(List<Author> authors) {
        Integer[] arr = {1, 2, 3, 4};
        Stream<Integer> stream = Arrays.stream(arr);
        stream.distinct()
                .filter(integer -> integer > 2)
                .forEach(System.out::println);

        Stream.of(arr)
                .filter(integer -> integer > 2)
                .forEach(System.out::println);


    }

    /**
     * 打印所有年龄小于18的作家的名字,去重
     */
    private static void test01(List<Author> authors) {
        authors.stream()
                .distinct()
                .filter(author -> author.getAge() < 18)
                .forEach(author -> System.out.println(author.getName()));
    }


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

        List<Book> books1 = new ArrayList<>();
        List<Book> books2 = new ArrayList<>();
        List<Book> books3 = new ArrayList<>();

        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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值