函数式编程Java函数式编程学习

Posted 三笠·阿卡曼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了函数式编程Java函数式编程学习相关的知识,希望对你有一定的参考价值。

函数式编程-Stream流

函数式编程思想


概述

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

优点

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

Lambda表达式

概念

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

核心原则

(参数列表) -> 代码

例子一

new Thread(new Runnable() 

	public void run()
		System.out.println("you nerver know,or you don't care");
	
).start();

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

new Thread(() -> 
		System.out.println("you nerver know,or you don't care");
	
).start();

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

例子二

public static int caculateNum(IntBinaryOperator operator) 
    int a = 20;
    int b = 30;
    return operator.applyAsInt(a, b);

转换成Lambda表达式

int j = caculateNum((a,b) -> 
     return a + b;
);

例子三

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

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

printNum((testValue) -> testValue % 2 == 0);

例子四

 public static <R> R typeConver(Function<String,R> function)
     String str = "1235";
     R result = function.apply(str);
     return result;

调用时候的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);
);

例子五

现有方法定义如下,其中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);
    

Lambda写法:

foreachArr((int value) -> 
    System.out.println("Lambda IntConsumer:" + value);
);

Lambda表达式的省略规则

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

Stream流


概述

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

案例数据准备

导入lombok依赖

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
</dependencies>
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author 
    //id
    private Long id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List<Book> books;

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

    //分类
    private String category;

    //评分
    private Integer score;

    //简介
    private String intro;


    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;
    

快速入门

需求

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

实现

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

常用操作

创建流

  • 单列集合:集合对象.stream();
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
  • 数组:Arrays.stream(数组)或者使用Stream.of来创建;
Integer[] arr = 1,2,3,4,5;
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream2 = Stream.of(arr);
  • 双列集合:转换成到单列集合再创建
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); 

中间操作

filter

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

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

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

List<Author> authors = getAuthors();

//打印所有作家的姓名
authors.stream()
        .map(author -> author.getName())
        .forEach(System.out::println);
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()));

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

limit

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

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

//对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年终最大的两个作家的姓名
List<Author> authors = getAuthors();

authors.stream()
       .distinct()
       .sorted()
       .limit(2)
       .forEach(author -> System.out.println(author.getName()));
skip

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

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

List<Author> authors = getAuthors();

//打印除了年龄最大作家外的其他作家,要求不能有重复元素,并且按照年龄降序;
authors.stream()
        .distinct()
        .sorted()
        .skip(1)
        .forEach(author -> System.out.println(author.getName()));
flatMap

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

  • 例一
    打印所有书籍的名字,要求对重复的元素进行去重
//打印所有书籍的名字,要求对重复的元素进行去重
List<Author> authors = getAuthors();

authors.stream()
        .flatMap(author -> author.getBooks().stream())
        .distinct()
        .forEach(Book::getName);
  • 例二
    打印现有数据的所有分类,要求对分类进行去重,不能出现这种格式:“哲学,爱情”
//打印现有数据的所有分类,要求对分类进行去重,不能出现这种格式:"哲学,爱情"
List<Author> authors = getAuthors();

authors.stream()
        .flatMap(author -> author.getBooks().stream())
        .distinct()
        .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
        .distinct()
        .forEach(System.out::println);

以上是关于函数式编程Java函数式编程学习的主要内容,如果未能解决你的问题,请参考以下文章

函数式编程Java函数式编程学习

函数式编程Java函数式编程学习

函数式编程Java函数式编程学习

RxJS 与 函数式编程 - 函数式编程

跟上 Java 8 : 函数式编程

预售┃Scala与Clojure函数式编程模式:Java虚拟机高效编程