• 【函数式编程】Java函数式编程学习


    函数式编程-Stream流

    函数式编程思想

    概述

    面向对象思想关注的是用什么对象完成什么事情,而函数式编程思想就类似于数学中的函数,主要关注的是对数据进行了什么操作

    优点

    • 代码简洁,开发快;
    • 接近自然语言,易于理解;
    • 易于进行“并发编程”;

    Lambda表达式

    概念

    Lambda是JDK8之后的一个语法躺,可以看成是一种语法糖,对某些匿名内部类的写法进行简化,是函数式编程思想的一个重要体现,让我们不用关注是什么对象,更关注的是对数据进行了什么操作;

    核心原则

    (参数列表) -> {代码}

    例子一
    new Thread(new Runnable() {
    
    	public void run(){
    		System.out.println("you nerver know,or you don't care");
    	}
    }).start();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    可以使用Lambda的格式对其进行修改,修改后如下:

    new Thread(() -> {
    		System.out.println("you nerver know,or you don't care");
    	}
    ).start();
    
    • 1
    • 2
    • 3
    • 4

    原则:什么时候匿名内部类也可以用Lambda表达式简化呢?如果匿名内部类是只有一个接口的匿名内部类,而且只有一个接口需要被重写;
    也就是说,一个接口就一个方法,那还关注方法名干嘛啊哈哈;

    例子二
    public static int caculateNum(IntBinaryOperator operator) {
        int a = 20;
        int b = 30;
        return operator.applyAsInt(a, b);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    转换成Lambda表达式

    int j = caculateNum((a,b) -> {
         return a + b;
    });
    
    • 1
    • 2
    • 3
    例子三
    public static void printNum(IntPredicate predicate) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int i : arr) {
            if (predicate.test(i)) {
                System.out.println(i);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    调用的时候转换成Lambda表达式

    printNum((testValue) -> testValue % 2 == 0);
    
    • 1
    例子四
     public static <R> R typeConver(Function<String,R> function){
         String str = "1235";
         R result = function.apply(str);
         return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    调用时候的lambda写法:

    1.
    Integer result = typeConver(new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {
            return Integer.valueOf(s);
        }
    });
    
    2.
    typeConver((String s) -> {
       return Integer.valueOf(s);
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    例子五

    现有方法定义如下,其中IntConsumer是一个接口。先使用匿名内部类的写法调用该方法。

    public static void foreachArr(IntConsumer consumer){
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i : arr) {
           consumer.accept(i);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Lambda写法:

    foreachArr((int value) -> {
        System.out.println("Lambda IntConsumer:" + value);
    });
    
    • 1
    • 2
    • 3

    Lambda表达式的省略规则

    • 参数类型可以省略
    • 方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
    • 方法只有一个参数时小括号可以省略
    • 以上这些规则都记不住也可以省略不记

    Stream流


    概述

    Java8的Steam使用的是函数式编程模式,如他名字一样,它可以用来对集合或数字进行链状流式操作,可以更加方便的对集合或者数组进行操作;

    案例数据准备

    导入lombok依赖
    <dependencies>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.16version>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @EqualsAndHashCode//用于后期的去重使用
    public class Author {
        //id
        private Long id;
        //姓名
        private String name;
        //年龄
        private Integer age;
        //简介
        private String intro;
        //作品
        private List<Book> books;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode//用于后期的去重使用
    public class Book {
        //id
        private Long id;
        //书名
        private String name;
    
        //分类
        private String category;
    
        //评分
        private Integer score;
    
        //简介
        private String intro;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
        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<>();
    
            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;
        }
    
    • 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

    快速入门

    需求

    可以调用getAuthors方法获取到作家的集合,需要打印所有年龄小于18的作家的名字,并且注意去重;

    实现
    authors.stream()  //将集合转换成流
                    .distinct() //集合元素去重
                    .filter(author -> author.getAge() < 18)
                    .forEach(author -> System.out.println(author.getName()));
    
    • 1
    • 2
    • 3
    • 4

    常用操作

    创建流
    • 单列集合:集合对象.stream();
    List<Author> authors = getAuthors();
    Stream<Author> stream = authors.stream();
    
    • 1
    • 2
    • 数组:Arrays.stream(数组)或者使用Stream.of来创建;
    Integer[] arr = {1,2,3,4,5};
    Stream<Integer> stream = Arrays.stream(arr);
    Stream<Integer> stream2 = Stream.of(arr);
    
    • 1
    • 2
    • 3
    • 双列集合:转换成到单列集合再创建
    Map<String, Integer> map = new HashMap<>();
    map.put("蜡笔小新",19);
    map.put("火影忍者",17);
    map.put("进击的巨人",16);
    
    //map转换成单列集合再获取stream流
    Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
    //获取年龄大于16的数据~
    stream.filter(item -> item.getValue() > 16).forEach(System.out::println); 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    中间操作
    filter

    可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中;
    如,打印所有姓名长度大于1的作家的姓名:

    List<Author> authors = getAuthors();
    //印所有姓名长度大于1的作家的姓名
    authors.stream()
            .filter(author -> author.getName().length() > 1)
            .forEach(author -> System.out.println(author.getName()));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    map

    可以把对流中的元素进行计算或者转换
    打印所有的作家的姓名

    List<Author> authors = getAuthors();
    
    //打印所有作家的姓名
    authors.stream()
            .map(author -> author.getName())
            .forEach(System.out::println);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    distinct

    可以去除流中的重复元素
    如:打印所有作家的姓名,并且要求其中不能有重复元素;

      注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的,所以需要注意重写equals方法

      sorted

      可以对流中的元素进行排序
      如:对流中的元素按照年龄进行降序排序,并且要求不能有重复元素

      List<Author> authors = getAuthors();
      //对流中的元素按照年龄进行降序排序,并且要求不能有重复元素,调用空参的sorted方法
      authors.stream()
             .distinct()
             .sorted() //操作的对象要实现Comparable接口
             .forEach(author -> System.out.println(author.getAge()));
      //调用有参的sorted方法
      authors.stream()
             .distinct()
             .sorted((o1,o2) -> o2.getAge() - o1.getAge())
             .forEach(author -> System.out.println(author.getAge()));
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

      注意:如果调用空参的sorted方法需要流中的元素对象实现Comparable接口,重写compareTo方法

      limit

      可以设置流的最大长度,超出的部分将被抛弃

      如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年终最大的两个作家的姓名

      //对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年终最大的两个作家的姓名
      List<Author> authors = getAuthors();
      
      authors.stream()
             .distinct()
             .sorted()
             .limit(2)
             .forEach(author -> System.out.println(author.getName()));
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      skip

      跳过流中的前n个元素,返回剩下的元素

      如:打印除了年龄最大作家外的其他作家,要求不能有重复元素,并且按照年龄降序;

      List<Author> authors = getAuthors();
      
      //打印除了年龄最大作家外的其他作家,要求不能有重复元素,并且按照年龄降序;
      authors.stream()
              .distinct()
              .sorted()
              .skip(1)
              .forEach(author -> System.out.println(author.getName()));
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      flatMap

      map只能将一个对象转化成另外一个对象来作为流中的元素,而flatMap可以把一个对象转化成多个对象作为流中的元素

      • 例一
        打印所有书籍的名字,要求对重复的元素进行去重
      //打印所有书籍的名字,要求对重复的元素进行去重
      List<Author> authors = getAuthors();
      
      authors.stream()
              .flatMap(author -> author.getBooks().stream())
              .distinct()
              .forEach(Book::getName);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 例二
        打印现有数据的所有分类,要求对分类进行去重,不能出现这种格式:“哲学,爱情”
      //打印现有数据的所有分类,要求对分类进行去重,不能出现这种格式:"哲学,爱情"
      List<Author> authors = getAuthors();
      
      authors.stream()
              .flatMap(author -> author.getBooks().stream())
              .distinct()
              .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
              .distinct()
              .forEach(System.out::println);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      终结操作
      forEach

      对流中的元素进行遍历操作,通过传入的参数去指定对遍历到的元素进行什么具体操作

      例子: 输出所有作家的名字

      	List<Author> authors = getAuthors();
      	//输出所有作家的名字
      	
      	authors.stream()
      	        .distinct()
      	        .forEach(author -> System.out.println(author.getName()));
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      count

      可以用来获取当前流中元素的个数

      例子:打印作家的所有书籍的数目,注意删除重复元素

      	List<Author> authors = getAuthors();
      	
      	//打印作家的所有书籍的数目,注意删除重复元素
      	long count = authors.stream()
      				        .flatMap(author -> author.getBooks().stream())
      				        .distinct()
      				        .count();
      	System.out.println(count);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      max&min

      可以用来获取流中的最值

      例子:分别获取这些作家的所出书籍的最高分和最低分并打印

      	List<Author> authors = getAuthors();
      	
      	//分别获取这些作家的所出书籍的最高分和最低分并打印
      	Optional<Integer> max = authors.stream()
      							        .flatMap(author -> author.getBooks().stream())
      							        .distinct()
      							        .map(Book::getScore)
      							        .max((Integer::compareTo));
      	
      	System.out.println(max.get());
      	
      	Optional<Integer> min = authors.stream()
      					                .flatMap(author -> author.getBooks().stream())
      					                .distinct()
      					                .map(Book::getScore)
      					                .min(Integer::compareTo);
      
           System.out.println(min.get());
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      重中之重之collect

      将当前流转换成一个集合

      例一:获取一个存放所有作者名字的集合

      	List<Author> authors = getAuthors();
      
          //获取一个存放所有作者名字的集合
          List<String> authorNameList = authors.stream()
                  .map(Author::getName)
                  .distinct()
                  .collect(Collectors.toList());
          System.out.println(authorNameList);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8

      例二:获取一个所有书名的Set集合

      	List<Author> authors = getAuthors();
      	
          //获取一个所有书名的Set集合
          Set<Book> collect = authors.stream()
                  .flatMap(author -> author.getBooks().stream())
                  .collect(Collectors.toSet());
          System.out.println(collect);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7

      例三:获取一个Map集合,map的key为作者名,value为List

      	List<Author> authors = getAuthors();
      	
      	//获取一个Map集合,map的key为作者名,value为List
      	authors.stream()
      			.distinct()
      	        .collect(Collectors.toMap(Author::getName, Author::getBooks));
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      查找与匹配
      anyMatch

      可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型
      例子:判断是否有年龄在29以上的作家

      	//判断是否有年龄在29以上的作家
          List<Author> authors = getAuthors();
      
          boolean flag = authors.stream()
                  .anyMatch(new Predicate<Author>() {
                      @Override
                      public boolean test(Author author) {
                          return author.getAge() > 29;
                      }
                  });
          //true
          System.out.println(flag);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      allMatch

      可以用来判断是否都符合匹配条件,结果为boolean类型,如果都符合结果为true,否则为false

      例子:判断是否所有的作家都是成年人

      	//判断是否所有的作家都是成年人
          List<Author> authors = getAuthors();
      
          boolean b = authors.stream()
                  .allMatch(author -> author.getAge() > 18);
      	//false
          System.out.println(b);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      noneMatch

      可以判断流中的元素是否都不符合匹配条件,如果都不符合结果为true,否则结果为false

      例子:判断作家是否都没有超过100岁的

      	List<Author> authors = getAuthors();
      
           //判断作家是否都没有超过100岁的
           boolean flag = authors.stream()
                   .noneMatch(author -> author.getAge() >= 100);
      
           System.out.println(flag);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      findAny

      获取流中的任意一个元素,该方法没有办法保证获取的一定是流中的第一个元素

      例子:获取任意一个年纪大于18的作家,如果存在就输出他的名字

      	List<Author> authors = getAuthors();
      
          //获取任意一个年纪大于18的作家,如果存在就输出他的名字
          Optional<Author> authorOptional = authors.stream()
                  .filter(author -> author.getAge() > 18)
                  .findAny();
      
          authorOptional.ifPresent(author -> System.out.println(author.getName()));
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      findFirst

      获取流中的第一个元素

      例子:获取一个年龄最小的作家,并输出他的姓名

          List<Author> authors = getAuthors();
      
          //获取一个年龄最小的作家,并输出他的姓名
          Optional<Author> optionalAuthor = authors.stream()
                  .sorted((o1, o2) -> o2.compareTo(o1))
                  .findFirst();
      
          optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      reduce 归并

      对流中的数据按照在指定的计算方式计算出一个结果(缩减操作)

      reduce的作用是把stream中的元素组合起来,可以传入一个初始值,会按照指定的计算方式依次拿流中的元素和在初始化值的基础上进行计算,计算结果再和后面的元素计算;

      内部计算方式如下:

      
          T result = identity;
          for(T element : this stream)
          	result = accumulator.apply(result, element);
      
          return result
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6

      其中identity就是可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是可以通过方法参数来确定的;

      例子:

      • 使用reduce求所有作者年龄的和
          	//使用reduce求所有作者年龄的和
          	List<Author> authors = getAuthors();
      
              Integer sum = authors.stream()
                      .map(Author::getAge)
                      .reduce(0, (result, element) -> result + element);
      
              System.out.println(sum);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 使用reduce求所有作者中年龄的最大值
      	//使用reduce获取所有作者中的最大值
              List<Author> authors = getAuthors();
      
              Integer maxValue = authors.stream()
                      .map(Author::getAge)
                      .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
      
              System.out.println(maxValue);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 使用reduce求所有作者年龄的最小值
      
      		//使用reduce获取所有作者中的最小值
              List<Author> authors = getAuthors();
      
              Integer minValue = authors.stream()
                      .map(Author::getAge)
                      .reduce(Integer.MAX_VALUE, (result, element) -> result < element ? result : element);
      
              System.out.println(minValue);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
    • 相关阅读:
      非常详细的git-flow分支管理流程配置及使用
      6.3二叉树的层序遍历(LC102,LC107-M)
      二三维电子沙盘数字沙盘虚拟现实开发教程第14课
      Linux 内核参数:slabinfo
      Godot 4 教程《勇者传说》依赖注入 学习笔记(0):环境配置
      Zookeeper的ZAB协议原理详解
      计算机网络篇之TCP滑动窗口
      使用SpaceDesk实现iPad成为电脑拓展屏(保姆级教程)
      HYSES data北美多源水文气象数据
      对iOS开发中的链接器ld64和-ld_classic的深入理解
    • 原文地址:https://blog.csdn.net/cjl_xupt/article/details/126448176