【函数式编程】

本文详细介绍了Java8中的函数式编程特性,包括Lambda表达式的使用,如创建、参数省略、语法格式等;Stream流的操作,如创建、中间操作(filter、map、distinct等)和终结操作(forEach、count、collect等);以及Optional类在处理可能为空的对象时的优势。此外,还讲解了函数式接口的概念及其在代码中的应用。
摘要由CSDN通过智能技术生成

函数式编程

1. 概述

1.1为什么要学习?
  • 能够看懂公司里的代码
  • 大数量下处理集合效率高
  • 代码可读性高
  • 消灭嵌套地狱
1.2 函数式编程思想
1.2.1 概念

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

1.2.2 优点
  • 代码简洁,开发快速
  • 接近自然语言,易于理解
  • 易于”并发编程“

2. Lambda表达式

2.1 概述

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

2.2 核心原则

可推导可省略

2.3 基本格式
(参数列表)->{代码};
->: lambda操作符或箭头操作符
->: 左边: lambda 形参列表(其实就是接口中的抽象方法的形参列表)
->: 右边: lambda 体(其实就是重写的抽象方法的方法体)
例一:

我们在创建线程并启动时可以使用匿名内部类的写法:

  Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("我爱北京天安门");
            }
        };
  runnable.run();

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

 Runnable runnable2=()-> System.out.println("我爱北京天安门");
 runnable2.run();
例二:

Comparator类比大小,之前的写法

Comparator<Integer> objectComparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return Integer.compare(o1, o2);
    }

};
int compare = objectComparator.compare(25, 12);
System.out.println(compare);

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

Comparator<Integer> comparator=(o1,o2)->Integer.compare(o1,o2);
int compare2 = comparator.compare(12, 25);
System.out.println(compare2);

可以使用f方法引用得格式对其进行修改,修改后如下:

Comparator<Integer> comparator3=Integer::compare;
int compare3 = comparator.compare(12, 25);
System.out.println(compare3);
2.4 Lambda 表达式的使用:(分为6种情况)
2.4.1 语法格式一:无参,无返回值

​ 之前得写法

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("我爱北京天安门");
    }
};
runnable.run();

​ lmbda写法

Runnable runnable2=()-> System.out.println("我爱北京天安门");
runnable2.run();
2.4.2 语法格式二: lambda 需要一个参数,但是没有返回值

​ 之前得写法

Consumer<String> con = new Consumer<String>(){
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
};
con.accept("张三");

​ lmbda写法

Consumer<String> con2 = (String s)->{System.out.println(s);};
con2.accept("李四");
2.4.3 语法格式三:类型推断;(String s)-> 变成(s),类型是根据Consumer<String>推断出来的(语法二简化)

​ 简化后得lambda表达式

Consumer<String> con1 = (s)->System.out.println(s);
con1.accept("李四");
2.4.4 语法格式四:lambda 若只需要一个参数时,参数的小括号可以省略 (s)->变成s->(语法二简化)

​ 简化后得lambda表达式

Consumer<String> con1 = s->System.out.println(s);
con1.accept("李四");
2.4.5 语法格式五: lambda 需要两个或以上的参数,多条执行语句,并且可以有返回值

​ 之前得写法

Comparator<Integer> objectComparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        System.out.println(01);
        System.out.println(02);
        return Integer.compare(o1, o2);
    }

};
int compare = objectComparator.compare(25, 12);
System.out.println(compare);

​ lmbda写法

Comparator<Integer> comparator6=(o1, o2)->{
    System.out.println(01);
    System.out.println(02);
    return Integer.compare(o1, o2);
};
int compare1 = comparator6.compare(12,25);
System.out.println(compare1);
2.5 省略规则
  • 参数类型可以省略
  • 方法体只有一句代码时大括号return和唯一一句代码得分号可以省略
  • 方法只有一个参数时小括号可以省略
  • 以上这些规则都记不住也可以省略不记

3. Stream流

3.1 概述

​ java8得Stream使用得时函数式编程模式,如同它得名字一样,它可以被用来对集合或数组进行链状流式得操作。可以方便得让我们对集合或数组操作;

3.2 案例数据准备

<dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
@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;
}

3.3 快速入门

3.3.1 需求

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

3.3.2 实现
@Test
public void test(){
    List<Author> authors = getAuthors();
    /**
     * 之前的写法
     */
    authors.stream()
            .distinct()
            .filter(new Predicate<Author>() {
                        @Override
                        public boolean test(Author author) {
                            return author.getAge()<18;
                        }
                    })
            .forEach(new Consumer<Author>() {
                @Override
                public void accept(Author author) {
                    System.out.println(author.getName());
                }
            });
    /**
     * lambda写法
     */
    authors.stream()
            .distinct()
            .filter(author -> author.getAge()<18)
            .forEach(author -> System.out.println(author.getName()));

}

lambda调试:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y5KoSiXY-1679409857602)(C:\Users\root\AppData\Roaming\Typora\typora-user-images\image-20230307210556411.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7XaMip0h-1679409857603)(C:\Users\root\AppData\Roaming\Typora\typora-user-images\image-20230307210658599.png)]

3.4 常用操作

3.4.1 创建流
① 单列集合

集合对象.stream( );

 @Test
    public void test(){
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .filter(author -> author.getAge()<18)
                .forEach(author -> System.out.println(author.getName()));

    }
② 数组

Arrays.stream(数组)或者使用Stream.of来创建

    @Test
    public void test2(){
        Integer[] arr = {1,1, 2, 3, 4, 5};
        Stream<Integer> stream = Arrays.stream(arr);
        stream.distinct()
               .filter(s->s>2)
               .forEach(System.out::println);

    }
③ 双列集合

转换成单列集合后再创建

@Test
public void test2(){
    Integer[] arr = {1,1, 2, 3, 4, 5};
    Stream<Integer> stream = Arrays.stream(arr);
    stream.distinct()
           .filter(s->s>2)
           .forEach(System.out::println);

}
3.4.2 中间操作
① filter

可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。

例如:打印所有姓名长度大于1的作家的姓名

@Test
public void test(){
    List<Author> authors = StreamDome.getAuthors();
    authors.stream()    
            .filter(author -> author.getName().length() > 1)
            .forEach(System.out::println);

}
② map

可以把对流中的元素进行计算或转换

例如:打印所有作家的名字

@Test
public void test2(){
    List<Author> authors = StreamDome.getAuthors();
    authors.stream()
            .map(author -> author.getName())
            .forEach(System.out::println);

}
③ distinct

可以去除流中的重复元素

例如:打印所有作家的姓名,并且要求其中不能有重复元素

@Test
public void test3(){
    List<Author> authors = 创建流_01.getAuthors();
    authors.stream()
            .distinct()
            .forEach(System.out::println);

}

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

实体类中的@EqualsAndHashCode就相当于实体中的重写了equals和hashCode方法;

④ sorted

可以对流中的元素进行排序

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

@Test
public void test4(){
    List<Author> authors = 创建流_01.getAuthors();
    authors.stream()
            .distinct()
            .sorted()
            .forEach(System.out::println);
}

注:如果调用空参的sorted()方法,需要流中的元素是实现了Comparable

@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 o.getAge() - this.getAge();
        //这样就是升序
        //return this.getAge() - o.getAge();
    }
}
@Test
public void test4(){
    //有参构造(lambda)
    authors.stream()
            .distinct()
            .sorted(comparingInt(author -> author.getAge()))
            .forEach(author -> System.out.println(author.getAge()));
    //有参构造(方法引用)
    authors.stream()
            .distinct()
            .sorted(comparingInt(Author::getAge))
            .forEach(author -> System.out.println(author.getAge()));
}
⑤ limit

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

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

@Test
public void test5(){
    List<Author> authors = 创建流_01.getAuthors();
    authors.stream()
            .distinct()
            .sorted(comparingInt(Author::getAge))
            .limit(2)
            .forEach(author -> System.out.println(author.getName()));

}
⑥ skip

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

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

@Test
public void test6(){
    List<Author> authors = 创建流_01.getAuthors();
    authors.stream()
            .distinct()
            .sorted((o1, o2) -> o2.getAge() - o1.getAge())
            .skip(1)
            .forEach(author -> System.out.println(author.getName()));

}
⑦ flatMap

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

@Test
public void test7(){
    List<Author> authors = 创建流_01.getAuthors();
    //例一:打印所有书籍的名字。要求对重复的元素进行去重。
    authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .forEach(book -> System.out.println(book.getName()));
    System.out.println("********************************************");
   //例二:打印现有数据的所有分类。要求对分类进行去重。不能出现这样格式:哲学,爱情
    authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
            .distinct()
            .forEach(c-> System.out.println(c));

}
3.4.3 终结操作
① forEach

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

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

@Test
public void test1(){
    List<Author> authors = 创建流_01.getAuthors();
    authors.stream()
            .map(author -> author.getName())
            .distinct()
            .forEach(name-> System.out.println(name));

}
② count

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

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

@Test
public void test2(){
    List<Author> authors = 创建流_01.getAuthors();
    long count = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .count();
    System.out.println(count);

}
③ min&max

可以用来获取流中的最值

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

@Test
public void test3(){
    List<Author> authors = 创建流_01.getAuthors();
    Optional<Integer> max = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .map(Book::getScore)
            .distinct()
            .max((o1, o2) -> o1 - o2);
    Optional<Integer> min = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .map(Book::getScore)
            .distinct()
            .min((o1, o2) -> o1 - o2);
    System.out.println(max.get());
    System.out.println(min.get());

}
④ collect

把当前流转换成一个集合

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

@Test
public void test4(){
    List<Author> authors = 创建流_01.getAuthors();
    //例一:获取一个存放所有作者名字的List集合
    List<String> collect = authors.stream()
            .map(author -> author.getName())
            .collect(Collectors.toList());
    System.out.println(collect);
}

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

@Test
public void test4(){
    List<Author> authors = 创建流_01.getAuthors();
    //例二:获取一个所有书名的Set集合
    Set<String> collect1 = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .map(book -> book.getName())
            .collect(Collectors.toSet());
    System.out.println(collect1);
}

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

@Test
public void test4(){
    List<Author> authors = 创建流_01.getAuthors();
   //例三:获取一个map集合,map的key为作者名,value为List
    Map<String, List<Book>> collect2 = authors.stream()
            .distinct()
            .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
    System.out.println(collect2);
}
⑤ 查找与匹配
1、anyMatch

可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型

@Test
public void test5(){
    List<Author> authors = 创建流_01.getAuthors();
    boolean b = authors.stream()
            .anyMatch(author -> author.getAge() > 29);
    System.out.println(b);
}
2、allMatch

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

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

@Test
public void test5_2(){
    List<Author> authors = 创建流_01.getAuthors();
    boolean b = authors.stream()
            .allMatch(author -> author.getAge() > 5);
    System.out.println(b);
}
3、noneMatch

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

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

@Test
public void test5_3(){
    List<Author> authors = 创建流_01.getAuthors();
    boolean b = authors.stream()
            .noneMatch(author -> author.getAge() > 100);
    System.out.println(b);
}
4、finaAny

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

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

@Test
public void test5_4(){
    List<Author> authors = 创建流_01.getAuthors();
    Optional<Author> any = authors.stream()
            .filter(author -> author.getAge() > 18)
            .findAny();
   any.ifPresent(System.out::println);
}
5、findFirst

获取流中的第一个元素

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

@Test
public void test5_5(){
    List<Author> authors = 创建流_01.getAuthors();
    Optional<Author> any = authors.stream()
        .filter(author -> author.getAge() > 10)
        .findFirst();
    any.ifPresent(System.out::println);
}
⑥ reduce归并

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

reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。

reduce两个参数的重载形式内部的计算方式如下:

T result = identity;
for (T element : this stream)
	result = accumulator.apply(result, element)
return result;

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

例一:使用reduce求所有作者年龄的和

@Test
public void test6(){
    List<Author> authors = 创建流_01.getAuthors();
    Integer reduce = authors.stream()
                    .distinct()
                    .map(author -> author.getAge())
                    .reduce(0, (result, element) -> result + element);
    System.out.println(reduce);
}

例二:使用reduce求所有作者中年龄的最大值

@Test
public void test6_2(){
    List<Author> authors = 创建流_01.getAuthors();
    Integer reduce = authors.stream()
            .distinct()
            .map(author -> author.getAge())
            .reduce(Integer.MIN_VALUE,(result, element)->result<element?element:result);
    System.out.println(reduce);
}

例三:使用reduce求所有作者中年龄的最小值

@Test
public void test6_3(){
    List<Author> authors = 创建流_01.getAuthors();
    Integer reduce = authors.stream()
            .distinct()
            .map(author -> author.getAge())
            .reduce(Integer.MAX_VALUE,(result, element)->result<element?result:element);
    System.out.println(reduce);
}
3.5 注意事项
  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)

  • 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)

  • 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)


4. Optional

4.1 概述

我们在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断

例如:

@Test
public void test(){
    Author author = getAuthor();
    if(author!=null){
        System.out.println(author.getName());
    }

}
public static Author getAuthor() {
    Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟真理的祖安人", null);
    return null;
}
  • 尤其是对象中的属性还是一个对象的情况下。这种判断会更多。

  • 而过多的判断语句会让我们的代码显得臃肿不堪。

  • 所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。

  • 并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。

4.2 使用

4.2.1 创建对象

Optional就好像是包装类,可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常

我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题。

@Test
public void test_2(){
    Author author = getAuthor();
    Optional<Author> author1 = Optional.ofNullable(author);
    author1.ifPresent(author2 -> System.out.println(author2));

}
  public static Author getAuthor() {
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟真理的祖安人", null);
        return author;
 }
/**
 * Optional 方式
 */
@Test
public void test_3(){
    Optional<Author> author21 = getAuthor2();
    author21.ifPresent(author2 -> System.out.println(author2.getName()));

}
public static Optional<Author> getAuthor2() {
    Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟真理的祖安人", null);
    return Optional.ofNullable(author);
}

在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。

如果你确定一个对象不是空的则可以使用Optional的静态方法of来把数据封装成Optional对象。

@Test
public void test_3(){
    Author author22 = getAuthor();
    Optional<Author> author221 = Optional.of(author22);
    author221.ifPresent(author2 -> System.out.println(author2.getName()));

}

但是一定要注意,如果使用of的时候传入的参数必须不为null。(尝试下传入null会出现什么结果)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MKISKu09-1679409857604)(C:\Users\root\AppData\Roaming\Typora\typora-user-images\image-20230314101917155.png)]

4.2.2 安全消费值

我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值。

这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。

例如,以下写法就优雅的避免了空指针异常。

@Test
public void test_1(){
    Author author = getAuthor();
    Optional<Author> author1 = Optional.ofNullable(author);
    author1.ifPresent(author2 -> System.out.println(author2));

}
4.2.3 获取值

如果我们想获取值自己进行处理可以使用get方法获取,但是不推荐。因为当Optional内部的数据为空的时候会出现异常

@Test
public void test2_1(){
    Author author22 = getAuthor();
    Optional<Author> author221 = Optional.ofNullable(author22);
    Integer age = author221.get().getAge();
    System.out.println(age);

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-086x8qIz-1679409857604)(C:\Users\root\AppData\Roaming\Typora\typora-user-images\image-20230314103948158.png)]

4.2.4 安全获取值

如果我们期望安全的获取值。我们不推荐使用get方法,而是使用Optional提供的以下方法。

  • orElseGet

    获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回。

    @Test
    public void test4(){
        Optional<Author> author21 = getAuthor2();
        Author author = author21.orElseGet(()->new Author());
        System.out.println(author);
    
    }
    
  • orElseThrow

    获取数据,如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。

@Test
public void test4_2(){
    Optional<Author> author21 = getAuthor2();
    try {
        Author author = author21.orElseThrow(()->new RuntimeException("数据为null"));
        System.out.println(author);
    }catch (RuntimeException e){
        e.printStackTrace();
    }


}
4.2.5 过滤

我们可以使用filter方法对数据进行过滤。如果原本是有数据的,但是不符合判断,也会变成一个无数据的Optional对象。

@Test
public void test5(){
    Optional<Author> author21 = getAuthor2();
    author21
            .filter(author -> author.getAge()>18)
            .ifPresent(author -> System.out.println(author.getName()));

}
4.2.6 判断

我们可以使用isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空,返回值为true。但是这种方式并不能体现Optional的好处,更推荐使用ifPresent方法

@Test
public void test6(){
    Optional<Author> author21 = getAuthor2();
    if (author21.isPresent()) {
        System.out.println(author21.get().getName());
        System.out.println(author21.get().getAge());

    }

}
4.2.7 数据转换

Optional还提供了map可以让我们对数据进行转换,并且转换得到的数据也是被Optional包装好的,保证了我们的使用安全。

@Test
public void test7(){
    Optional<Author> author21 = getAuthor2();
    author21.map(author -> author.getBooks())
            .ifPresent(bookList-> bookList.stream()
                                          .forEach(book -> System.out.println(book.getName())));
}

5.函数式接口

4.1概述:

只有一个抽象方法的接口我们称之为函数接口。

JDK的函数式接口都加上**@FunctionalInterface**注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。

4.2 自定义函数式接口
/**
 * 函数接口:有且只有一个抽象方法的接口,称之为函数接口
 * 当然接口中可以包含其他的方法(默认,静态,私有)
 *
 * @FunctionalInterface注解
 *  作用:可以检测接口是否是一个函数式接口;
 *    是:编译成功;
 *    否:编译失败(接口中没有抽象方法。或者抽象方法的个数多余1个)
 */
@FunctionalInterface
public interface MySun {

     void sun(String s);
}
4.3 四大核心函数式接口
4.3.1 概述
  • Consumer: 消费性接口:void accept(T t); 有参数没有返回值;

  • Supplier: 供给型接口:T get(); 有返回值没有参数;

  • Function<R,T>: 函数式接口(R 是返回值类型,T是参数类型):R apply; 有返回值有参数;

  • Predicate:断言型接口:boolean test(T t);

4.3.2 使用
Consumer: 消费性接口:
// todo Consumer<T>: 消费性接口: void accept(T t); 有参数没有返回值;
/**
 * 之前的写法
 */
@Test
public void test1_1(){
    //匿名内部类转换成lambda 快捷键 alt+回车
    happy(10000, new Consumer<Double>() {
        @Override
        public void accept(Double d) {
            System.out.println("学习太累了,去天上人间买瓶矿泉水,价格为"+d+"元");
        }
    });
}
   /**
     * lambda写法
     */
    @Test
   public void test1(){
       happy(10000,d-> System.out.println("学习太累了,去天上人间买瓶矿泉水,价格为"+d+"元"));
   }
//消费方法
public void happy(double money, Consumer<Double> consumer){
    consumer.accept(money);
}
Supplier: 供给型接口
// todo Supplier<T>: 供给型接口:T get(); 有返回值没有参数;(生成十个随机数存到集合中去) 
/**
 * 之前的写法
 */
@Test
public void test2_1(){
    List<Integer> numList = getNumList(10, new Supplier<Integer>() {
        @Override
        public Integer get() {
            return (int)Math.random() * 100;
        }
    });
    numList.stream().forEach(System.out::println);

}
    /**
     * lambda写法
     */
    @Test
    public void test2(){
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        numList.stream().forEach(System.out::println);

    }
//参数一:随后数的个数
public List<Integer> getNumList(int a , Supplier<Integer> supplier){
    List<Integer> list = new ArrayList<>();
    for (int i = 0; i < a; i++) {
        list.add(supplier.get());
    }
    return list;
}
Function<R,T>: 函数式接口
// todo Function<R,T>: 函数式接口(R 是返回值类型,T是参数类型):R apply<T t>; 有返回值有参数; (String转Integer)
@Test
public void test4(){
    /**
     * 之前的写法
     */
    Integer integer = typeConver(new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {
            return Integer.parseInt(s);
        }
    });
    System.out.println(integer);
    /**
     * lambda写法
     */
    Integer integer1 = typeConver((s) -> Integer.parseInt(s));
    System.out.println(integer1);
    /**
     * 方法引用
     */
    Integer integer2 = typeConver(Integer::parseInt);
    System.out.println(integer2);
}
public static <R> R typeConver(Function<String,R> function){
    String str="1235";
    R apply = function.apply(str);
   return apply;
}
Predicate:断言型接口
//todo Predicate<T>:断言型接口: boolean test(T t);
/**
 * 之前的写法
 */
@Test
public void test3(){
    List<String> filterList2 = Arrays.asList("南京","北京","东京","河南","上海");
    filterString(filterList2, new Predicate<String>() {
        @Override
        public boolean test(String s) {
            return s.contains("京");
        }
    });
}
/**
 * lambda写法
 */
@Test
public void test3_1(){
    List<String> filterList2 = Arrays.asList("南京","北京","东京","河南","上海");
    filterString(filterList2, s -> s.contains("京"));
}
//根据给定的规则,过滤集合中的字符串。此规则由Predicate的方法决定的
public List<String> filterString(List<String> list, Predicate<String> pre){
    List<String> filterList = new ArrayList<>();
    for (String filter:list) {
        if (pre.test(filter)) {

            filterList.add(filter);

        }
    }
    System.out.println(filterList);
    return filterList;
}

6.方法引用

我们在使用Lambda时,如果方法体只有一个方法调用的话(包括构造方法),我们可以用方法引用进一步简化代码。

6.1 推荐用法

我们在使用lambda时不需要考虑什么时候用方法引用,用哪种方法引用,方法引用的格式是什么。我们只需要在写完lambda方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可。

当我们方法引用使用的多了慢慢的也可以直接写出方法引用。

6.2 基本格式

类名或者对象名: :方法名

6.3 语法详解(了解)

6.3.1 引用静态方法

其实就是引用类的静态方法

格式

类名: :方法名

使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。

例如:如下代码就可以用方法引用进行简化

@Test
private static void test31() {
    List<Author> authors = 创建流_01.getAuthors();
    //优化前
    authors.stream()
            .map(author -> author.getAge())
            .filter(age -> age > 20)
            .map(obj -> String.valueOf(obj))
            .forEach(s -> System.out.println(s));

    //优化后
    authors.stream()
            .map(Author::getAge)
            .filter(age -> age > 20)
            .map(String::valueOf)
            .forEach(System.out::println);
}
6.3.2 引用对象的实例方法

格式

对象名 ::方法名

使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这话代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法

例如:

@Test
private static void test2() {
    List<Author> authors = 创建流_01.getAuthors();
    StringBuilder sb = new StringBuilder();
    //优化前
    authors.stream()
            .map(author -> author.getName())
            .forEach(new Consumer<String>() {
                @Override
                public void accept(String name) {
                    sb.append(name);
                }
            });

    //优化后
    authors.stream()
            .map(author -> author.getName())
            .forEach(sb::append);

    System.out.println(sb.toString());
}
6.3.4 构造器引用

如果方法体中的一行代码是构造器的话就可以使用构造器引用。
格式

类名 : : new

使用前提

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的构造方法,并且我们把要重写的抽象方法中的所有的参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器。

private static void test3() {
    List<Author> authors = 创建流_01.getAuthors();
    //优化前
    authors.stream()
            .map(new Function<Author, String>() {
                @Override
                public String apply(Author author) {
                    return author.getName();
                }
            })
            .map(new Function<String, StringBuilder>() {
                @Override
                public StringBuilder apply(String name) {
                    return new StringBuilder(name);
                }
            })
            .map(new Function<StringBuilder, String>() {
                @Override
                public String apply(StringBuilder sb) {
                    return sb.append("三更").toString();
                }
            })
            .forEach(new Consumer<String>() {
                @Override
                public void accept(String name) {
                    System.out.println(name);
                }
            });

    //优化后
    authors.stream()
            .map(Author::getName)
            .map(StringBuilder::new)
            .map(sb -> sb.append("三更").toString())
            .forEach(System.out::println);
}

7、高级用法

7.1 基本数据类型优化

我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。

即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。

所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法。

例如:mapToInt,mapToLong,mapToDouble,flatMapToInt,flatMapToDouble等。

private static void test34() {
    List<Author> authors = 创建流_01.getAuthors();
    //map
    authors.stream()
            .map(Author::getAge)
            .forEach(new Consumer<Integer>() {
                @Override
                public void accept(Integer age) {
                    System.out.println(age);
                }
            });
    //mapToInt
    authors.stream()
            .mapToInt(author -> author.getAge())//优化
            .forEach(new IntConsumer() {
                @Override
                public void accept(int age) {
                    System.out.println(age);
                }
            });
}

7.2 并行流

当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完成。如果我们自己去用代码实现的话其实会非常的复杂,并且要求你对并发编程有足够的理解和认识。而如果我们使用Stream的话,我们只需要修改一个方法的调用就可以使用并行流来帮我们实现,从而提高效率。

parallel方法可以把串行流转换成并行流。

private static void test35() {
    //串行流
    Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    Stream<Integer> stream1 = Stream.of(arr);
    Integer sum1 = stream1
            .filter(num -> num > 5)
            .reduce((result, element) -> result + element)
            .get();
    System.out.println(sum1);

    //并行流
    Stream<Integer> stream2 = Stream.of(arr);
    Integer sum2 = stream2
            .parallel()//转换
            .filter(num -> num > 5)
            .reduce((result, element) -> result + element)
            .get();
    System.out.println(sum2);

}

也可以通过parallelStream直接获取并行流对象。

private static void test36() {
    //串行流对象
    List<Author> authors1 = 创建流_01.getAuthors();
    authors1.stream()
            .map(author -> author.getAge())
            .map(age -> age + 10)
            .filter(age -> age > 18)
            .map(age -> age + 2)
            .forEach(System.out::println);

    System.out.println("=========================");
    //并行流对象
    List<Author> authors2 = 创建流_01.getAuthors();
    authors2.parallelStream()
            .map(author -> author.getAge())
            .map(age -> age + 10)
            .filter(age -> age > 18)
            .map(age -> age + 2)
            .forEach(System.out::println);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值