函数式编程(lambda表达式)

函数式编程

概述

作用:

  • 代码可读性高
  • 消灭嵌套地狱
  • 大数据下处理效率高

优点:

  • 代码简洁,开发快速
  • 易于理解

函数式编程思想:它主要关注的是对数据进行了什么操作(面向对象思想需要关注用什么对象完成什么事情)

Lambda表达式

概述:jdk1.8新特性,对某些匿名内部类写法进行简化,他是函数式编程思想的一个重要体现

核心原则:可推导可省略

基本格式:(参数列表)->{代码}

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

例子一

  • 匿名内部类是否可以使用lambda优化条件(1.是一个接口 2. 接口里面只有一个抽象方法需要重写
public class lambdaTest {
    public static void main(String[] args) {
        new Thread(new Runnable() {  //这里使用了匿名内部类(关注方法的参数和方法体)
            @Override
            public void run() {
                System.out.println("run方法被执行了");
            }
        }).start();

    }
  • 使用lambda的格式对其进行修改,修改后如下
public class lambdaTest {
    public static void main(String[] args) {//这里使用了匿名内部类(关注方法的参数和方法体)
        new Thread(() -> {
            System.out.println("run方法被执行了");
        }).start();
    }
    
    
     new Thread(() -> System.out.println("run方法被执行了")).start();
  • 刚开始的时候使用匿名内部类的方法来写

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

例子二

  • 匿名内部类
 public static void main(String[] args) {
int i = calculateNum(new IntBinaryOperator() {
        @Override
        public int applyAsInt(int left, int right) {
            return left+right;
        }
    });
        System.out.println(i);//30
    }
}
    public static int calculateNum(IntBinaryOperator operator){
        int a = 10;
        int b = 20;
        return operator.applyAsInt(a, b);
    }

优化

  • alt + enter
   int i = calculateNum((int left, int right)-> {
            return left+right;
    });
        System.out.println(i);//30
    }

        
int i = calculateNum((left, right) -> left+right);
        System.out.println(i);//30
    }//最终

例子三

  • 匿名内部类写法
public static void main(String[] args) {       
printNum(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return value%2==0;//如果下面传过来的参数,这里条件成立,下面就会打印
            }
        });
}
    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);//输出2.4.6.8.10
            }
        }

    }
  • lambda写法
public static void main(String[] args) {  
	printNum((int value)-> {
    	        return value%2==0;//如果下面传过来的参数,这里条件成立,下面就会打印
      	  });
}

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

例子四

function是一个接口,使用匿名内部类的写法调用该方法

public static void main(String[] args) {    
Integer r =   typeConver(new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return Integer.valueOf(s);
            }
}
        });
        System.out.println(r);
    }

lambda写法

public static void main(String[] args) {     
Integer r =   typeConver((String s)-> {
            return Integer.valueOf(s);
    });
    

  • 通过方法的泛型,我们可以实现接口的时候传入不同的参数
     Integer r =   typeConver((String s)-> {
            return Integer.valueOf(s);
    });

    String a =  typeConver((String b)-> {
            return b + "lwh";
     });
        System.out.println(a);
}

     String a =  typeConver(b->b + "lwh");

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

例子五

IntConsumer是一个接口,使用匿名内部类写法调用该方法

        foreachArr(new IntConsumer() {
            @Override
            public void accept(int value) {
                System.out.println(value);
            }
        });

    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(value);
    });

foreachArr(value -> System.out.println(value));//最终

省略规则

  • 参数类型可以直接省略
  • 方法体只有一句代码return和唯一一句代码的分号可以省略
  • 方法只有一个参数可以省略

Stream流

概述:java8的stream使用的是函数式编程模式,跟他名字一样用来对集合或者数组进行链状流式操作,更方便我们对集合或者数组操作。

  • 写完匿名内部类后,鼠标选中当前new的参数,alt+enter转成lambda表达式

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

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()//把集合转换成流
                .distinct()//重复的元素排除
                .filter(author -> author.getAge()<18)//条件
                .forEach(author -> 	System.out.println(author.getName()));
    }

常用操作

创建流
  • 先使用匿名内部类,看参数类型,再alt+enter转换成lambda

  • 单列集合:集合对象.stream()

List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream()//把集合转换成流
  • ctrl+alt+n 收起方法

  • forEach是终结方法
    
  • 数组:Arrays.stream(数组)或者使用Stream.of来创建

         Integer[] arr = {1,2,3,4,4,5};
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream = Stream.of(arr);

  • 双列集合:转换成集合在创建
    private static void test02() {
        Map<String,Integer> map = new HashMap<>();
        map.put("梁伟浩", 24);
        map.put("喜洋洋", 34);
        map.put("迪迦", 44);

        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        Stream<Map.Entry<String, Integer>> stream = entries.stream();

        stream.filter(new Predicate<Map.Entry<String, Integer>>() {
            @Override
            public boolean test(Map.Entry<String, Integer> entry) {
                return entry.getValue()>24;
            }
        }).forEach(new Consumer<Map.Entry<String, Integer>>() {
            @Override
            public void accept(Map.Entry<String, Integer> entry) {
                System.out.println(entry.getKey()+"==="+entry.getValue());
            }
        });
    }

转换成lambda

    private static void test02() {
        Map<String,Integer> map = new HashMap<>();
        map.put("梁伟浩", 24);
        map.put("喜洋洋", 34);
        map.put("迪迦", 44);

        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        Stream<Map.Entry<String, Integer>> stream = entries.stream();

        stream.filter(entry -> entry.getValue()>24)
                .forEach(entry -> System.out.println(entry.getKey()+"==="+entry.getValue()));
    }
中间操作
filter

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

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

把流中的元素进行计算或者转换。

例如:

​ 打印所有作家的姓名

    private static void test04() {
        //打印所有作家的姓名
        List<Author> authors = getAuthors();
//        authors.stream()
                .map(author -> author.getName())
//                .forEach(s -> System.out.println(s));

        authors.stream()
               .map(author -> author.getAge())//通过map转换成Integer,年龄
                .map(age->age+10)//通过map年龄加10,第一个参数age自定义最好要见名知意
                .forEach(age-> System.out.println(age));

    }

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

distinct
@EqualsAndHashCode//用于后期的去重使用

去除重复的元素

    private static void test05() {

        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .forEach(author -> System.out.println(author.getName()));

    }

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

sorted

对流中的元素进行排序

例如:

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

     List<Author> authors = getAuthors();
        //        对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
            authors.stream()
                    .distinct()
                    .sorted()
                    .forEach(author -> System.out.println(author.getAge()));
//实体实现了接口
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();
    }
}
        List<Author> authors = getAuthors();
        //        对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
            authors.stream()
                    .distinct()
                    .sorted((o1, o2) -> o2.getAge()-o1.getAge())
                    .forEach(author -> System.out.println(author.getAge()));
  • 先写匿名内部类,再转换成lambda,因为不接口的参数

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

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(2)
                .forEach(author -> System.out.println(author.getName()));
flatMap

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

例一:

​ 打印所有书籍的名字。要求对重复的元素进行去重。

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

        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> System.out.println(book.getName()));

例二:

​ 打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情

        List<Author> authors = getAuthors();
            authors.stream()
                    .flatMap(author -> author.getBooks().stream())
                    .distinct()//对流的书籍去重
                    .flatMap(book -> Arrays.stream(book.getCategory().split(",") ))//通过Arrays.stream转换成流对象
                    .distinct()//对流中的分类去重
                    .forEach(catrgory -> System.out.println(catrgory));

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

终结操作
forEach

对流中进行遍历

例子:

​ 输出所有作家的名字

 List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getName())//先把作家转换成作家名字
                .distinct()
                .forEach(author -> System.out.println(author));//参数名,见名知意,自己起即可
count

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

例子:

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

      List<Author> authors = getAuthors();
        long count = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .count();
        System.out.println(count);

  • max&min 可以用来或者流中的最值。

    例子:

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

     //书籍最高分和最低分
        //stream<author> --> stream<books> -->stream<integer> -->求值(一个对象转换成多个用flatmap)
        List<Author> authors = getAuthors();
        Optional<Integer> max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .max((o1, o2) -> o1 - o2);

        authors = getAuthors();
        Optional<Integer> min = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .min((o1, o2) -> o1 - o2);
        System.out.println(max.get());
        System.out.println(min.get());
collect

把流转换成一个集合

​ 把当前流转换成一个集合。

例子:

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

        List<Author> authors = getAuthors();
        List<String> collect = authors.stream()
                .map(author -> author.getName())
                .collect(Collectors.toList());//转换成list集合
        System.out.println(collect);

​ 获取一个所有书名的Set集合。

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

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

//        获取一个Map集合,map的key为作者名,value为List<Book>
        List<Author> authors = getAuthors();
        Map<String, List<Book>> map = authors.stream()
                .distinct()
                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
        System.out.println(map);
查找与匹配
anyMatch

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

例子:

​ 判断是否有年龄在29以上的作家

       List<Author> authors = getAuthors();
        boolean anyMatch = authors.stream()
                .anyMatch(author -> author.getAge() > 49);
        System.out.println(anyMatch);
noneMatch

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

例子:

​ 判断作家是否都没有超过100岁的。

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

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

例子:

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

//        List<Author> authors = getAuthors();
//         Optional<Author> optionalAuthor = authors.stream()
//                 .filter(author -> author.getAge()>18)
//                 .findAny();
//         optionalAuthor.isPresent(author-> System.out.println(author.getName()));
//         optionalAuthor.isPresent(author->System.out.println(author.getName()));//如果有值存在,就执行


        List<Author> authors = getAuthors();
        Optional<Author> optionalAuthor = authors.stream()
                .filter(author -> author.getAge()>18)
                .findAny();

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

​ 获取流中的第一个元素。

例子:

​ 获取一个年龄最小的作家,并输出他的姓名。

         List<Author> authors = getAuthors();
        final Optional<Author> first = authors.stream()
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .findFirst();
        first.ifPresent(author -> System.out.println(author.getName()));
reduce归并

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

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

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

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

求所有作家年龄的和

      List<Author> authors = getAuthors();
         Integer reduce = authors.stream()
                .distinct()
                .map(author -> author.getAge())
                .reduce(0, (result, element) -> result + element);
        System.out.println(reduce);

求所有作家最大年龄

   List<Author> authors = getAuthors();
        final Integer max = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
        System.out.println(max);

求所有作家最小年龄

        List<Author> authors = getAuthors();
        final Integer min = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
        System.out.println(min);

​ reduce一个参数的重载形式内部的计算

 	 boolean foundAny = false;
     T result = null;
     for (T element : this stream) {
         if (!foundAny) {
             foundAny = true;
             result = element;
         }
         else
             result = accumulator.apply(result, element);
     }
     return foundAny ? Optional.of(result) : Optional.empty();

​ 如果用一个参数的重载方法去求最小值代码如下:

        //        使用reduce求所有作者中年龄的最小值
        List<Author> authors = getAuthors();
        Optional<Integer> minOptional = authors.stream()
                .map(author -> author.getAge())
                .reduce((result, element) -> result > element ? element : result);
        minOptional.ifPresent(age-> System.out.println(age));

Optional

概述

非空判断

​ 例如:

        Author author = getAuthor();
        if(author!=null){
            System.out.println(author.getName());
        }

​ 尤其是对象中的属性还是一个对象的情况下。这种判断会更多。

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

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

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

创建对象

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

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

    public static void main(String[] args) {
//        Author author = getAuthors();
//        Optional<Author> authorOptional = Optional.ofNullable(author);
//        authorOptional.ifPresent(author2 -> System.out.println(author2.getName()));

        Optional<Author> authorOptional = getAuthorOptional();
        authorOptional.ifPresent(author -> System.out.println(author.getName()));


    }
    public static Optional<Author> getAuthorOptional(){
        Author author = new Author(1L,"梁伟浩",24,"123123",null);
          
            return Optional.ofNullable(author);
    }
    public static Author getAuthors(){
        Author author = new Author(1L,"梁伟浩",24,"123123",null);
            return author;//这里返回的是null,所以调用方法都是null
    }
安全消费值

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

  • orElseGet

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

            Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
            Author author1 = authorOptional.orElseGet(() -> new Author());
    
  • orElseThrow

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

            Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
            try {
                Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("author为空"));
                System.out.println(author.getName());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
    
    过滤

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

            Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
            authorOptional.filter(author -> author.getAge()>100).ifPresent(author -> System.out.println(author.getName()));
    
    
    判断isPresent
        private static void testFilter() {
            Optional<Author> authorOptional = getAuthorOptional();
            Optional<Author> optionalAuthor = authorOptional.filter(author -> author.getAge() > 88);
    
        }
        private static void testIspresent() {
            Optional<Author> authorOptional = getAuthorOptional();
                if (authorOptional.isPresent()){
                    System.out.println(authorOptional.get().getName());
                    System.out.println(authorOptional.get().getAge());
                }
    
        }
    
    
数据转换

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

例如我们想获取作家的书籍集合。

    private static void testMap() {
        Optional<Author> authorOptional = getAuthorOptional();
        Optional<List<Book>> optionalBooks = authorOptional.map(author -> author.getBooks());
        optionalBooks.ifPresent(books -> System.out.println(books));
    }

函数式接口

概述

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

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

常见函数式接口

  • ​ Consumer 消费接口

    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hneDT0G0-1651644046851)(C:/Users/LWH/Desktop/函数式编程/函数式编程.assets/image-20211028145622163-16354041894551.png)]

  • ​ Function 计算转换接口

  • 根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PbU0CdLf-1651644046851)(C:/Users/LWH/Desktop/函数式编程/函数式编程.assets/image-20211028145707862-16354042291112.png)]

  • ​ Predicate 判断接口

    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E8LeLNi3-1651644046852)(C:/Users/LWH/Desktop/函数式编程/函数式编程.assets/image-20211028145818743-16354043004393.png)]

  • ​ Supplier 生产型接口

    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I36GyLnh-1651644046853)(C:/Users/LWH/Desktop/函数式编程/函数式编程.assets/image-20211028145843368-16354043246954.png)]

常用的默认方法

  • and

    我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件

    例如:

    打印作家中年龄大于17并且姓名的长度大于1的作家。

        List<Author> authors = getAuthors();
        Stream<Author> authorStream = authors.stream();
        authorStream.filter(new Predicate<Author>() {
            @Override
            public boolean test(Author author) {
                return author.getAge()>17;
            }
        }.and(new Predicate<Author>() {
            @Override
            public boolean test(Author author) {
                return author.getName().length()>1;
            }
        })).forEach(author -> System.out.println(author));

or

我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。

例如:

打印作家中年龄大于17或者姓名的长度小于2的作家。

//        打印作家中年龄大于17或者姓名的长度小于2的作家。
        List<Author> authors = getAuthors();
        authors.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;
                    }
                })).forEach(author -> System.out.println(author.getName()));

negate

Predicate接口中的方法。negate方法相当于是在判断添加前面加了个! 表示取反

例如:

打印作家中年龄不大于17的作家。

//        打印作家中年龄不大于17的作家。
        List<Author> authors = getAuthors();
        authors.stream()
                .filter(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getAge()>17;
                    }
                }.negate()).forEach(author -> System.out.println(author.getAge()));

方法引用

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

推荐用法

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

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

基本格式

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

语法详解(了解)

引用类的静态方法

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

格式
类名::方法名
使用前提

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

例如:

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

        List<Author> authors = getAuthors();

        Stream<Author> authorStream = authors.stream();
        
        authorStream.map(author -> author.getAge())
                .map(age->String.valueOf(age));

注意,如果我们所重写的方法是没有参数的,调用的方法也是没有参数的也相当于符合以上规则。

优化后如下:

        List<Author> authors = getAuthors();

        Stream<Author> authorStream = authors.stream();

        authorStream.map(author -> author.getAge())
                .map(String::valueOf);
      List<Author> authors = getAuthors();
        authors.stream()
                .map(Author::getName)
                .map(StringBuilder::new)
                .map(sb->sb.append("-三更").toString())
                .forEach(System.out::println);

高级用法

基本数据类型优化

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

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

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

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

    private static void test27() {

        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getAge())
                .map(age -> age + 10)
                .filter(age->age>18)
                .map(age->age+2)
                .forEach(System.out::println);

        authors.stream()
                .mapToInt(author-> author.getAge())//这里返回值是int不用装箱拆箱浪费资源
                .map(age->age+10)
                .filter(age->age>18)
                .map(age->age+2)
                .forEach(System.out::println);
    }

并行流

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

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

    private static void test28() {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
        Integer integer = stream
                .parallel()//串行转换成并行流,多个线程执行,不加的话就单个线程执行
                .peek(integer1 -> System.out.println(integer1 +Thread.currentThread().getName()))//这个方法是查看当前线程调用情况
                .filter(num -> num > 5)
                .reduce((result, element) -> result + element)
                .get();
        System.out.println(integer);
    }

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

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

        List<Author> authors = getAuthors();
        authors.parallelStream()
                .map(author -> author.getAge())
                .map(age -> age + 10)
                .filter(age->age>18)
                .map(age->age+2)
                .forEach(System.out::println);

注意事项

  • stream,要有终结操作,没有终结操作中间操作不会执行
  • 一个流只能进行一次终结操作哦,已经关闭了,不能再次使用
  • stream不会修改源数据
  • ctrl+鼠标可以查看当前的参数类型
  • 只有是流才可以继续.链式编程,是其他类型不行
  • 装箱拆箱(integer)耗费资源
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Java中的战斗机

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

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

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

打赏作者

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

抵扣说明:

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

余额充值