JDK8新特性-学习笔记

雀语笔记连接:
https://www.yuque.com/g/u22538081/ghlpft/zcbyis/collaborator/join?token=pofOuJabmo9rgKvS# 邀请你查看文档「函数式编程-jdk新特性」

为什么学?

看懂公司的代码
大数量下处理集合效率高
代码可读性高
消灭嵌套地狱

概念

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

优点

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

lambda表达式

概念

语法糖
对某些匿名内部类的写法进行简化。
更关注我们对数据进行什么操作。

核心

可推导可省略

基本格式

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

例一

以前,创建线程启动匿名内部类的写法

new Thread(new Runnable() {
    
    
    @Override
    public void run() {
    
    
        System.out.println("新线程中run方法被执行了");
    }
}).start();

使用lambda后

		/**
		 * 什么时候可以用lambda简化呢?
		 * 	1、如果匿名内部类是一个接口
		 * 	2、并且这个接口中只有一个方法需要重写(有多个就不好判断重写哪个了)
		 * 	【关注参数和方法体】
		 */
		new Thread(()-> {
    
    
			System.out.println("lambda表达式");
		}).start();

例二

package lambda;

import java.util.function.IntBinaryOperator;

public class LambdaDemo01 {
    
    
	public static void main(String[] args) {
    
    
		/**
		 * 原来的写法
		 */
		int i = calculateNum(new IntBinaryOperator() {
    
    
			@Override
			public int applyAsInt(int left, int right) {
    
    
				// TODO Auto-generated method stub
				return left + right;
			}
		});
		System.out.println(i);
		
		/**
		 * 使用lambda表达式
		 */
		int j = calculateNum((int left,int right) -> {
    
    
			return left + right;
		});
		System.out.println(j);
	
	}
	//IntBinaryOperator 是函数式接口
	public static int calculateNum(IntBinaryOperator operator) {
    
    
		int a = 10;
		int b = 20;
		return operator.applyAsInt(a, b);
	}
}

idea快键,变lambda
在这里插入图片描述

idea快键,lambda变原样
在这里插入图片描述

例三

package lambda;

import java.util.function.IntBinaryOperator;
import java.util.function.IntPredicate;

public class LambdaDemo01 {
    
    
	public static void main(String[] args) {
    
    
		/**
		 * 原来的写法
		 */
		printNum(new IntPredicate() {
    
    
			
			@Override
			public boolean test(int value) {
    
    
				// TODO Auto-generated method stub
				return value%2 == 0;
			}
		});
		
		System.out.println("==================");
		
		/**
		 * 使用lambda表达式
		 */
		printNum((int value) -> {
    
    
			return value%2 == 0;
		});
		
	}
	//IntPredicate 是一个函数式接口
	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);
			}
		}
		
	}
	
}

例四

package lambda;

import java.util.function.Function;

public class LambdaDemo01 {
    
    
	public static void main(String[] args) {
    
    

		/**
		 * 原来方式
		 */
		 Integer result = typeConver(new Function<String, Integer>() {
    
    

			@Override
			public Integer apply(String t) {
    
    
				// TODO Auto-generated method stub
				return Integer.valueOf(t);
			}
			
		});
		 
		System.out.println(result);
		
		/**
		 * 使用lambda表达式
		 */
		Integer result2 = typeConver((String t) -> {
    
    
			return Integer.valueOf(t);
		});
		System.out.println(result2);
		
	}
	//Function 是一个函数式接口	
	public static <R> R typeConver(Function<String,R>function) {
    
    
		String str = "1235";
		R result = function.apply(str);
		return result;
	}
	
}

例五

package lambda;

import java.util.function.Function;
import java.util.function.IntConsumer;

public class LambdaDemo01 {
    
    
	public static void main(String[] args) {
    
    

		/**
		 * 原来方式
		 */
		foreachArr(new IntConsumer() {
    
    
			
			@Override
			public void accept(int value) {
    
    
				// TODO Auto-generated method stub
				System.out.println(value);
			}
		});
		 
		
		/**
		 * 使用lambda表达式
		 */
		foreachArr((int value) -> {
    
    
			System.out.println(value);
		});
	}
	//Function 是一个函数式接口	
	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);
		}
	}
}

省略规则

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

省略例子

package lambda;

import java.util.function.Function;
import java.util.function.IntConsumer;

public class LambdaDemo01 {
    
    
	public static void main(String[] args) {
    
    
		
		/**
		 * 使用lambda表达式
		 */
		foreachArr((int value) -> {
    
    
			System.out.println(value);
		});
		
		/**
		 * 省略后
		 */
		foreachArr(value -> System.out.println(value));
	}
	//Function 是一个函数式接口	
	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);
		}
	}
}

Stream流

1、概述

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

2、案例数据准备

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.22</version>
    </dependency>
</dependencies>

作者类

package com.sangeng;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.List;

@Data   //生成get和set
@NoArgsConstructor  //无参构造
@AllArgsConstructor //有参构造
@EqualsAndHashCode  //用于后期去重使用(重写equals和hashCode方法)
public class Author {
    
       //作者

    //id
    private Long id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List<Book> books;
}

图书类

package com.sangeng;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Book {
    
    //书
    //id
    private Long id;
    //书名
    private String name;
    //分类
    private String category; //哲学,小说
    //评分
    private Integer score;
    //简介
    private String intro;

}

数据

package com.sangeng;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamDemo {
    
    
    public static void main(String[] args) {
    
    

        List<Author> authors = getAuthors();
    }

    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> authorsList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));

        return authorsList;
    }
}

3、快速入门

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

实现:

package com.sangeng;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class StreamDemo {
    
    
    public static void main(String[] args) {
    
    

        List<Author> authors = getAuthors();
        //System.out.println(authors);

        //打印所有年龄小于18的作家名字,并且要注意去重
        //filter过滤
        //forEach遍历
        authors.stream()    //stream()把集合转换成流
            .distinct()     //distinct()去重
            .filter(author -> author.getAge() < 18) //filter过滤【名字小于18】
            .forEach(author -> System.out.println(author.getName()));   //forEach遍历
    }

    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> authorsList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));

        return authorsList;
    }
}

快键操作

debug Stream流

java内容变成方法
在这里插入图片描述

4、常规操作

1、创建流

单列集合:集合对象.Stream

List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();

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

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

双列集合:转换成单列集合后再创建

Map<String,Integer> map = new HashMap<>();
map.put("垃圾公司",19);
map.put("黑子",17);
map.put("日向源",16);
Stream<Map.Entry<String,Integer>> stream3 = map.entrySet().stream();//entrySet()把map集合key,value封装成Set
//上一句分开
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
Stream<Map.Entry<String, Integer>> stream4 = entrySet.stream();

2、中间操作

filter 过滤器

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

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

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

map

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

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

        // map 打印所有作家的名字
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getName())    //获取所有名字
                .forEach(name -> System.out.println(name));

        //map 所有年龄加10
        authors.stream()
                .map(author -> author.getAge())
                .map(age -> age + 10)
                .forEach(age -> System.out.println(age));

distinct

可以去除重复的元素

例如:
打印所有作家的名字,并且要求其中不能有重复元素。
注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以要注意重写equals方法

        //打印所有作家的名字,并且要求其中不能有重复元素
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct() //去重
                .forEach(author -> System.out.println(author.getName()));

sorted

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

例如:
对流中的元素按照年龄进行降序排序,并且要求不能有重复元素
注意:如果调用空参的sorted()方法,需要流中的元素实现了Comparable接口

 //对流中的元素按照年龄进行降序排序,并且要求不能有重复元素
 List<Author> authors = getAuthors();
 authors.stream()
         .sorted() //排序 无参sorted()使用排序需要实现Comparable排序接口
         .distinct() //去重
         .forEach(author -> System.out.println(author.getName()));

 authors.stream()
         .distinct()
         .sorted((o1,o2) -> o2.getAge() - o1.getAge())   //排序 有参sorted直接匿名内部类实现Comparable排序接口
         .forEach(author -> System.out.println(author.getName()));

无参sorted,流中的元素需要实现Comparable接口

package com.sangeng;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.List;

@Data   //生成get和set
@NoArgsConstructor  //无参构造
@AllArgsConstructor //有参构造
@EqualsAndHashCode  //用于后期去重使用(重写equals和hashCode方法)
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();
    }
}

limit

可以设置流的最大长度,超出的部分将被抛弃
例如:
对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家名字

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

skip

跳过流中的前n个元素,返回剩下的元素
例如:
打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序

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

flatMap

map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。
例一
打印所有书籍的名字,要求对重复的元素进行去重。

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

 System.out.println("==========");
 authors.stream()
         .map(author -> author.getBooks())// 使用map的话,一个作者的书籍返回一个集合,不是一个个的书籍对象。
         .distinct()
         .forEach(book -> System.out.println(book));

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

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

3、终结操作

forEach

对流中的元素进行遍历操作,我们通过传入参数去指定遍历到的元素进行什么具体操作
例子:
输出所有作家的名字

//forEach 输出所有作家的名字
List<Author> authors = getAuthors();
authors.stream()
    .map(author -> author.getName())
    .distinct()
    .forEach(name -> System.out.println(name));

count

可以用来获取当前流中元素的个数
例子:
打印这些作家的所出书籍的数目,注意删除重复元素

//count 打印这些作家的所出书籍的数目,注意删除重复元素
List<Author> authors = getAuthors();
long count = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .distinct() //书信息进行去重
    .map(book -> book.getName())
    .distinct() //书名进行去重(由于我的测试数据,书名相同,但是有些分类写的是不同的)
    .count();   //计算 所有书的个数
System.out.println(count);

//老师这个【可能是没想到书名相同,但是分类没相同,这个是测试数据没写好】
long count1 = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .distinct() //书信息进行去重
    .count();
System.out.println(count1);

max min

可以用来获取流中的最值
例子:
分别获取这些作家的所出书籍的最高分和最低分并打印。

//max min 分别获取这些作家的所出书籍的最高分和最低分并打印。
List<Author> authors = getAuthors();
Optional max = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .map(book -> book.getScore() )
    .max((score1,score2) -> score1-score2);
System.out.println("最高评分 " + max.get());

Optional min = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .map(book -> book.getScore() )
    .min((score1,score2) -> score1-score2);
System.out.println("最低评分 " + min.get());

collect

把当前流转化成一个集合
Collectors.toList()
Collectors.toSet()
Collectors.toMap(,) 【key和value】
例子:
获取一个存放说有作者名字的List集合。

//collect
//获取一个存放说有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> name = authors.stream()
    .map(author -> author.getName())
    .distinct()
    .collect(Collectors.toList());// 把流转换成List
System.out.println(name);

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

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

获取一个map集合,map的key为作者名,value为List 【要写两个函数式,key和value】

// 获取一个map集合map的key为作者名,value为List<Book> 【map的话就要写两个方法】
Map<String,List<Book>> collect = authors.stream()
    .distinct()
    //map 两个返回值用“,”隔开(返回key,返回value)
    .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(collect);

查找与匹配 anyMatch、allMatch、noneMatch

----------------匹配---------------

anyMatch

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

//anyMatch可以用来判断是否有任意符合匹配条件的元素,结果为Boolean类型
//例子:判断是否有年龄在29岁以上的作家
List<Author> authors = getAuthors();
Boolean test = authors.stream()
    .anyMatch(author -> author.getAge() > 29);
System.out.println(test);

allMatch

可以用来判断是否都符合匹配条件,结果为Boolean类型。如果都匹配结果为true,否则为false
例子:
判断是否所有作家都成年了

 //allMatch可以用来判断是否都符合匹配条件,结果为Boolean类型。如果都匹配结果为true,否则为false
 //例子:判断是否所有作家都成年了
 Boolean test2 = authors.stream()
         .allMatch(author -> author.getAge()>18);
 System.out.println(test2);
noneMatch

可以判断流中的元素是否都不符合匹配条件,如果都不符合结果为true,否则为false
例子:
判断作家是否都没超过100岁

 //noneMatch可以判断流中的元素是否都不符合匹配条件,如果都不符合结果为true,否则为false
 //例子:判断作家是否都没超过100岁
 Boolean test3 = authors.stream()
         .noneMatch(author -> author.getAge()>=100);
 System.out.println(test3);

----------------查找---------------

findAny

获取流中的任意一个元素。该方法没有保证获取的一定是流中的第一个元素。
例子:
获取任意一个大于18的作家,如果存在就输出他的名字

 //findAny 获取流中的任意一个元素。该方法没有保证获取的一定是流中的第一个元素。
 //例子:获取任意一个大于18的作家,如果存在就输出他的名字
 List<Author> authors = getAuthors();
 Optional<Author> optionalAny = authors.stream()
         .filter(author -> author.getAge() > 18)
         .findAny();//获取流中的任意满足条件的一个元素

 //有问题,年龄改成0,还是同一个人(不是说是随机的吗?怎么还是第一个,是我代码有问题,还是概率问题)
 optionalAny.ifPresent(author -> System.out.println(author.getName()));
        
findFirst

获取流中的第一个元素。
例子:
获取一个年龄最小的作家,并输出他的姓名

//findFirst 获取流中的第一个元素。
//例子:获取一个年龄最小的作家,并输出他的姓名
List<Author> authors = getAuthors();
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;

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

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

//reduce简单理解(模拟)
int[] arr = {
    
    1,2,3,4};
int resut = 0;// 初始值
for (int i : arr){
    
      
    resut = resut + 1;// 具体操作
}
System.out.println(resut);

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

//使用reduce求所有作者的年龄和
List<Author> authors = getAuthors();
Integer sum = authors.stream()
    .distinct() // 去重
    .map(author -> author.getAge()) //  获取所有年龄
    // (初始值,(附上初始值,要操作的元素))
    .reduce(0, (result, element) -> result + element);
System.out.println(sum);

使用reduce求所作者中年龄的最大值

 //使用reduce求所作者中年龄的最大值
 List<Author> authors = getAuthors();
 Integer max = authors.stream()  //其实max() 是封装好的reduce
         .distinct()
         .map(author -> author.getAge()) // 获取年龄
         //      初始值(最小值)      附上初始值,要操作的元素 -> 三目,算出最大值
         .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
 System.out.println(max);

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

//使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Integer min = authors.stream()
    .distinct()
    .map(author -> author.getAge())
    //      初始值(最大值)      附上初始值,要操作的元素 -> 三目,算出最小值
    .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);

  /*
  Optional<Integer> min = authors.stream().distinct().map(Author::getAge).reduce(Integer::min);
  System.out.println(min);
  */
System.out.println(min);

使用reduce一个参数的形式,求所有作者中年龄的最小值

// reduce一个参数的用法
//使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Optional<Integer> minOptional = authors.stream()
    .map(author -> author.getAge())
    //reduce一个参数,把第一个元素赋给初始值
    .reduce((result, element) -> result > element ? element : result);

minOptional.ifPresent(age -> System.out.println(age));

stream注意事项

惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
流是一次性的(一旦一个流对象经过一个终结操作后,这个流就不能再被使用)
不会影响原数据(我们在流中可以对数据做很多的处理,但是正常情况下是不会影响原来集合中的元素的,这往往也是我们期望的)

Optional

概述:

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

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

·尤其是对象中的属性还不是一个对象的情况下。这种判断会更多
·而过多的判断语句会让我们的代码显得臃肿不堪
·所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。
·并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。

Optional使用

创建对象

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

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

   Author author = getAuthor();
   Optional<Author> authorOptional = Optional.ofNullable(author);

全部

package com.sangeng;

import java.util.Optional;
import java.util.function.Consumer;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Author author = getAuthor();
        Optional<Author> authorOptional = Optional.ofNullable(author);
        // ifPresent如果存在(如果数据为null,这里是不会被消费的)
        authorOptional.ifPresent(author1 -> System.out.println(author1.getName()));
    }

    public static Author getAuthor(){
    
    
        Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
        return author;// return null;
    }
}

你可能会觉得还要加一行代码来封装数据比较麻烦,但是如果改造下getAuthor方法,让他的返回值就是封装好的Optional的话,我们在使用时就会方便很多。(推荐使用)

package com.sangeng;

import javax.swing.text.html.Option;
import java.util.Optional;
import java.util.function.Consumer;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<Author> authorOptional = getAuthorOptional();
        authorOptional.ifPresent(author -> System.out.println(author.getName()));
    }

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

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

如果你确定对象不是空的则可以使用Optional静态方法of来把数据封装成Optional对象(不建议使用)
重点

 Author author = getAuthor();
 Optional<Author> author1 = Optional.of(author);
package com.sangeng;

import javax.swing.text.html.Option;
import java.util.Optional;
import java.util.function.Consumer;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    

        Author author = getAuthor();
        Optional<Author> author1 = Optional.of(author);
        author1.ifPresent(author2 -> System.out.println(author2.getName()));

    }


    public static Author getAuthor(){
    
    
        Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
        return author;//return null;
    }
}

一定要注意,如果使用of的时候传入的参数必须不为null。(尝试下传入null会出现什么结果)
用of方法,数据为空,会报空指针异常java.lang.NullPointerException

如果一个方法返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional的静态方法empty来进行封装。

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

你觉得那个更方便呢?
我以后还是使用Optional.ofNullable()吧

安全消费

我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值.这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。
例如
以下写法就优雅的避免了空指针异常。

 Optional<Author> author1 = Optional.of(author);
 author1.ifPresent(author2 -> System.out.println(author2.getName()));

获取值

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

Optional<Author> author = getAuthorOptional();
Author author1 = author.get();

安全获取值

如果我们期望安全的获取值。我们不推荐使用get方法,而是使用Optional提供的以下方法。
orElseGet
获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回.
重点

Optional<Author> authorOptional = getAuthorOptional();
//如果有值,就返回Author。如果没有值就返回默认值orElseGet(设置默认值)
Author author = authorOptional.orElseGet(() -> new Author());
Optional<Author> authorOptional = getAuthorOptional();
//如果有值,就返回Author。如果没有值就返回默认值orElseGet(设置默认值)
Author author = authorOptional.orElseGet(() -> new Author(2L,"大雨",33,"一个从菜刀中明悟哲理的祖安人",null));
System.out.println(author.getName());

public static Optional<Author> getAuthorOptional(){
    
    
    Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
    //Author author = null;
    return author == null?Optional.empty():Optional.of(author);
}

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

Optiona1<Author> authoroptiona1 = Optional.ofNu1lable(getAuthor 0));
try {
    
    
    Author author = authoroptional.orElseThrow((Supplier<Throwable>) () ->
                                                new RuntimeException("author为空"));
    System.out .printIn(author .getName());
} catch (Throwable throwable) {
    
    
    throwable.printstackTrace();
};

实战测试

Optional<Author> authorOptional = getAuthorOptional();
try {
    
    
    //如果author,就输出author。如果为空,就抛出异常。
    Author author = authorOptional.orElseThrow(() -> new RuntimeException("数据为null"));
    System.out.println(author);
} catch (Throwable throwable) {
    
    
    throwable.printStackTrace();
}

public static Optional<Author> getAuthorOptional(){
    
    
    Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
    //Author author = null;
    return author == null?Optional.empty():Optional.of(author);
}

过滤

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

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

public static Optional<Author> getAuthorOptional(){
    
    
    Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
    //Author author = null;
    return author == null?Optional.empty():Optional.of(author);
}

判断

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

Optional<Author> authorOptional = getAuthorOptional();
if (authorOptional.isPresent()) {
    
    
    System.out.println(authorOptional.get().getName());
}

数据转换

Optional还提供了map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全
例如我们想获取作家的书籍集合。

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

Optional<Author> authorOptional = getAuthorOptional();
        Optional<List<Book>> optionalBooks = authorOptional.map(author -> author.getBooks());
        optionalBooks.ifPresent(books -> System.out.println(books));

总结

创建Optional:ofNullable
Optional authorOptional = Optional.ofNullable(author);
安全消费:ifPresent
authorOptional.ifPresent(author2 -> System.out.println(author2.getName()));

函数式接口

概述

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

常见函数式接口

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

@FunctionalInterface
public interface Consumer<T> {
    
    

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
    
    
        Objects.requireNonNull(after);
        return (T t) -> {
    
     accept(t); after.accept(t); };
    }

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

@FunctionalInterface
public interface Function<T, R> {
    
    

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
    
    
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

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

@FunctionalInterface
public interface Predicate<T> {
    
    

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
    
    
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

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

@FunctionalInterface
    public interface Supplier<T> {
    
    

        /**
        * Gets a result.
        *
        * @return a result
        */
        T get();
    }

![image.png](https://img-blog.csdnimg.cn/img_convert/b8949435efdda633d4b4c8fbd258902b.png#averageHue=#f3f3dc&clientId=u3b1cbb5a-c114-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=251&id=ua0206448&margin=[object Object]&name=image.png&originHeight=282&originWidth=1001&originalType=binary&ratio=1&rotation=0&showTitle=false&size=177121&status=done&style=none&taskId=u70a12f12-cc60-4b11-ba18-a6c487dedb0&title=&width=889.7777777777778)

常见的默认方法

and
我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件
例如:
打印作家中年龄大于17并且姓名的长度大于1的作家。

//打印作家中年龄大于17并且姓名的长度大于1的作家。
List<Author> authors = getAuthors();
authors.stream()
    .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));

方法引用

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

推荐方法

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

基本格式

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

语法详解

引用静态方法

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

类名::方法名

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

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

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

List<Author> authors = getAuthors();
authors.stream()
    .map(author -> author.getAge())
    .map(String::valueOf);

引用对象的实例方法

格式

对象名::方法名

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

List<Author> authors = getAuthors();
Stream<Author> authorstream = authors .stream();
StringBuilder sb = new StringBuilder();
authorstream.map(author -> author.getName())
    .forEach(name->sb.append(name));

优化后:

List<Author> authors = getAuthors();
Stream<Author> authorstream = authors .stream();
StringBuilder sb = new StringBuilder();
authorstream.map(author -> author.getName())
    .forEach(sb::append);

引用类的实例方法

格式

类名::方法名

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

package com.sangeng;

import java.util.List;

public class MethodDemo {
    
    
    interface UseString{
    
    
        String use(String str,int start,int length) ;
    }


    public static String subAuthorName(String str, UseString useString) {
    
    
        int start = 0;
        int length = 1;
        return useString.use(str, start, length);

    }
    public static void main(String[] args) {
    
    
        subAuthorName("三更草堂",new UseString() {
    
    
            @Override
            public String use(String str, int start, int length) {
    
    
                return str.substring(start,length);
            }
        });

    }

}

优化后:

package com.sangeng;

import java.util.List;

public class MethodDemo {
    
    
    interface UseString{
    
    
        String use(String str,int start,int length) ;
    }


    public static String subAuthorName(String str, UseString useString) {
    
    
        int start = 0;
        int length = 1;
        return useString.use(str, start, length);

    }
    public static void main(String[] args) {
    
    
        subAuthorName("三更草堂", String::substring);

    }

}

构造器引用

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

类名::new

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

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

优化后:

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

高级用法

基本数据类型优化

我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。
即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好修使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。
所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法.

例如: madTolnt,mapToLong,mapToDouble,flatMapTolnt,flatMapToDouble等。

  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())// 拆箱一次,Integer->int
                .map(age -> age +10) // 后面的都是int了,不用自动拆箱了。
                .filter(age -> age>18)
                .map(age -> age+2)
                .forEach(System.out::println);

并行流

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

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

Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
/*
Integer integer = stream.filter(num -> num > 5)
.reduce((result, element) -> result + element)
.get();
System.out.println(integer);
*/

//变成并行流(多线程完成操作)
Integer integer2 = stream.parallel() // parallel并行
    .peek(new Consumer<Integer>() {
    
     // peek调试用的
        @Override
        public void accept(Integer num) {
    
    
            System.out.println(num +Thread.currentThread().getName());//查看是否多线程执行
        }
    })
    .filter(num -> num > 5)
    .reduce((result, element) -> result + element)
    .get();
System.out.println(integer2);

也可以使用parallelStream方法直接获取并行流对象

List<Author> authors = getAuthors();
authors.parallelStream()	//直接变成并行流

猜你喜欢

转载自blog.csdn.net/m0_51315555/article/details/127913909