1. 函数式编程思想
面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。
1.1概念
面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。
1.2优点
①代码简洁,开发快速
②接近自然语言,易于理解
③易于"并发编程"
2. Lambda表达式
2.1 概念
Lambda是JDK8中一个语法糖。可以看成是一种语法糖,他可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。
2.2 核心原则
可推导可省略
2.3 基本格式
(参数列表) -> { 代码 }
2.4 练习
new Thread(new Runnable() {
public void run() {
System.out.println("runnable中的run方法");
}
}).start();
new Thread(
() -> {
System.out.println("runnable中的run方法执行了");
}
).start();
public static int calculateNum(IntBinaryOperator operator) {
int a = 20;
int b = 30;
return operator.applyAsInt(a, b);
}
int result1 = calculateNum(new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left + right;
}
});
int result = calculateNum((a, b) -> {
return a + b;
});
public static void printNum(IntPredicate predicate) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i : arr) {
if (predicate.test(i)) {
System.out.println(i);
}
}
}
printNum(new IntPredicate() {
@Override
public boolean test(int value) {
return value % 2 == 0;
}
});
printNum((item) -> item % 2 == 0);
public static int calculateNum(IntBinaryOperator operator) {
int a = 20;
int b = 30;
return operator.applyAsInt(a, b);
}
String typeCoverInt = typeCoverInt((result) -> result + "喵喵喵");
2.5 所需数据及对象
作家Author
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期去重
public class Author implements Comparable<Author> {
private Long id;
private String name;
private Integer age;
private String intro;
private List<Book> books;
@Override
public int compareTo(Author author) {
return this.getAge() - author.getAge();
}
}
书籍
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期去重
public class Book {
private Long id;
private String name;
private String category;
private Integer score;
private String intro;
}
初始化数据
// 初始化一些数据
private static List<Author> getAuthors() {
Author author1 = new Author(1L, "AAA", 18, "my introduction 1", null);
Author author2 = new Author(2L, "BBB", 19, "my introduction 2", null);
Author author3 = new Author(2L, "BBB", 19, "my introduction 2", null);
Author author4 = new Author(4L, "CCCC", 29, "my introduction 4", null);
Author author5 = new Author(5L, "D", 12, "my introduction 5", null);
List<Book> books1 = new ArrayList<>();
List<Book> books2 = new ArrayList<>();
List<Book> books3 = new ArrayList<>();
// 上面是作者和书
books1.add(new Book(1L, "书名1", "分类1,分类2,分类3", 45, "这是简介哦"));
books1.add(new Book(2L, "书名2", "分类2,分类6", 84, "这是简介哦"));
books1.add(new Book(3L, "书名3", "分类3", 83, "这是简介哦"));
books2.add(new Book(5L, "书名4", "分类4", 65, "这是简介哦"));
books2.add(new Book(6L, "书名5", "分类5", 89, "这是简介哦"));
books3.add(new Book(7L, "书名6", "分类5", 45, "这是简介哦"));
books3.add(new Book(8L, "书名7", "分类4", 44, "这是简介哦"));
books3.add(new Book(9L, "书名8", "分类3", 81, "这是简介哦"));
author1.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books2);
author4.setBooks(books3);
author5.setBooks(books2);
return new ArrayList<>(Arrays.asList(author1, author2, author3, author4, author5));
}
3. Stream流
3.1 概述
Java 8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。
3.2 创建流
单列集合
集合对象.stream()
Stream<Author> stream = authors.stream();
数组
Arrays.stream(数组)或者使用Stream.of来创建
Integer[] arr = {1,4,7,9,10};
Stream<Integer> streamArr = Arrays.stream(arr);
Stream<Integer> streamArr2 = Stream.of(arr);
双列集合
转换成单列集合后再创建
Map<String, Integer> map = new HashMap<>();
map.put("AAA",16);
map.put("BBB",17);
map.put("CCC",18);
Stream<Map.Entry<String, Integer>> streamMap = map.entrySet().stream();
3.3 中间操作
filter
可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
// 打印所有姓名长度大于3的作家姓名
authors.stream().filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getName().length() > 3;
}
})
.forEach(author -> {
System.out.println(author.getName());
});
map
可以把流中的元素进行计算或是转换
// 打印所有作家的姓名
authors.stream().forEach(author -> System.out.println(author.getName()));
System.out.println("=============================");
authors.stream().map(new Function<Author, String>() {
@Override
public String apply(Author author) {
return author.getName();
}
}).forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
authors.stream().map(author -> author.getAge()).map(age -> age + 1000).forEach(age -> System.out.println(age));
distinct
去除流中重复元素
// 打印所有作家的名称,并且其中不能要求重复
authors.stream()
.distinct()
.forEach(author -> System.out.println(author.getName()));
sorted
可以对流中的元素进行排序。
I
注意:如果调用空参的sorted()方法,需要流中的元素是实现了Comparable。
// 对流中的元素按照年龄进行降序排序,组并且求不能有重复的元素
authors.stream()
.distinct()
.sorted()
.forEach(author -> System.out.println(author.getName()+":"+author.getAge()));
authors.stream()
.distinct()
.sorted(new Comparator<Author>() {
@Override
public int compare(Author o1, Author o2) {
return o2.getAge() - o1.getAge();
}
})
.forEach(author -> System.out.println(author.getName()+":"+author.getAge()));
limit
可以设置流的最大长度,超出的部分将被抛弃。
// 对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名
authors.stream()
.distinct()
.sorted((o1, o2) -> o2.getAge() - o1.getAge())
.limit(2)
.forEach(author ->
System.out.println(author.getName()+" : "+author.getAge()));
skip
跳过流中的前n个元素,返回剩下的元素
// 打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序
authors.stream()
.distinct()
.sorted((o1, o2) -> o2.getAge() - o1.getAge())
.skip(1)
.forEach(author -> System.out.println(author.getName() + " : "+author.getAge()));
flatMap
map只能把一个对象转换成另一 个对象来作为流中的元素。 而flatMap可以把一个对象转换成多 个对象作为流中的元素。
// 打印所有书籍的名字。要求对重复的元素进行去重
authors.stream()
.flatMap(new Function<Author, Stream<Book>>() {
@Override
public Stream<Book> apply(Author author) {
return author.getBooks().stream();
}
})
.distinct()
.forEach(new Consumer<Book>() {
@Override
public void accept(Book book) {
System.out.println(book.getName());
}
});
authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.forEach(book -> System.out.println(book.getName()));
3.4 终结操作
forEach
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
// 输出所有作家的名字
authors.stream().map(author -> author.getName())
.distinct()
.forEach(name -> System.out.println(name));
count
可以用来获取当前流中元素的个数。
// 打印这些作家的所出书籍的数目,注意删除重复元素
long count = authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
max&min
可以用来或者流中的最值。
// 分别获取这些作家的所出书籍的最高分和最低分并打印
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((score1, score2) -> score1 - score2);
System.out.println(max.get());
Optional<Integer> min = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.min((score1, score2) -> score1 - score2);
System.out.println(min.get());
collect
把当前流转换成一个集合。
获取一个存放所有作者名字的List集合
List<String> nameList = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toList());
System.out.println(nameList);
获取一个所有书名的Set集合
Set<String> bookNameSet = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getName())
.collect(Collectors.toSet());
System.out.println(bookNameSet);
获取一个Map集合,map的key为作者名,value为List
Map<String, List<Book>> authorBookMap = authors.stream()
.distinct() // 去重,当key相同是报错,如:Duplicate key [Book(id=5, name=书名4, category=分类4, score=65, intro=这是简介哦), Book(id=6, name=书名5, category=分类5, score=89, intro=这是简介哦)]
.collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(authorBookMap);
查找与匹配
anyMatch
可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。
判断是否有年龄在29以上的作家
boolean flag = authors.stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(flag);
allMatch
可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。
例子:
判断是否所有的作家都是成年人
boolean allMatch = authors.stream()
.allMatch(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() >= 18;
}
});
System.out.println(allMatch);
noneMatch
可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false
判断作家是否都没有超过100岁的
boolean noneMatch = authors.stream()
.noneMatch(author -> author.getAge() > 100);
System.out.println(noneMatch);
findAny
获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。
获取任意年龄一个大于18的作家,如果存在就输出他的名字
Optional<Author> optionalAuthor = authors.stream()
.filter(author -> author.getAge() > 18)
.findAny();
optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
findFirst
获取流中的第一个元素。
获取一个年龄最小的作家,并输出他的姓名
Optional<Author> first = authors.stream()
.sorted((o1, o2) -> o1.getAge() - o2.getAge())
.findFirst();
first.ifPresent(author -> System.out.println(author.getName()));
reduce归并
对流中的数据按照指定的计算方式计算出一个结果。(缩减操作)
reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。
他内部的计算方式如下:
T result = identity;
for (T element : this stream)
result = accumulator.app1y(resu1t,element)
return result;
其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。
使用reduce求所有作者年龄的和
// 使用reduce求所有作者年龄的和
Integer reduce = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce(0, (result, element) -> result + element);
System.out.println(reduce);
使用reduce求所有作者中年龄的最大值
// 使用reduce求所有作者中年龄的最大值
Integer maxAge = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MIN_VALUE, new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer element) {
return result < element ? element : result;
}
});
System.out.println(maxAge);
使用reduce求所有作者中年龄的最小值
// 使用reduce求所有作者中年龄的最小值
Integer minAge = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer element) {
return result > element ? element : result;
}
});
System.out.println(minAge);
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求所有作者中年龄的最小值
Optional<Integer> optionalInteger = authors.stream()
.map(author -> author.getAge())
.reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer element) {
return result > element ? element : result;
}
});
optionalInteger.ifPresent(result -> System.out.println(result));
3.5 注意事项
- 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
- 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
- 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)
4. Optional
4.1 概述
我们在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断。
例如:
if (author != null) {
System.out.println(author.getName());
}
尤其是对象中的属性还是一个对象的情况下。这种判断会更多。
而过多的判断语句会让我们的代码显得臃肿不堪。
所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。
4.2 使用
4.2.1 创建对象
Optional就好像是包装类,可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常。
我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为nulI都不会出现问题。
Optional<Author> authorOptional = Optional.ofNullable(author);
可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下,让其的返回值就是封装好的Optional的话,我们在使用时就会方便很多。
而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。
如果确定一个对象不是空的则可以使用Optional的静态方法of来把数据封装成Optional对象。
Optional<Author> authorOptional = Optional.of(author);
但是一定要注意,如果使用of的时候传入的参数必须不为null。(尝试下传入null会出现什么结果)
author = null;
Optional<Author> authorOptional1 = Optional.of(author);
authorOptional1.ifPresent(author1 -> System.out.println(author1));
//异常
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.Optional.<init>(Optional.java:96)
at java.util.Optional.of(Optional.java:108)
如果一个方法的返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional的静态方法empty来进行封装。
Optional<Object> empty = Optional.empty();
4.2.2 安全消费值
我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值。这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。
例如,以下写法就优雅的避免了空指针异常
Optional<Author> authorOptional = Optional.ofNullable(author);
authorOptional.ifPresent(author1 -> System.out.println(author1.getName()));
4.2.3 获取值
如果我们想获取值自己进行处理可以使用get方法获取,但是不推荐。因为当Optional内部的数据为空的时候会出现异常。
Optional<Author> authorNull = Optional.ofNullable(author);
Author author1 = authorNull.get();
4.2.4 安全获取值
-
orElseGet:获取数据并且设置数据为空时的默认值,如果数据不为空就获取该数据,为空则获取默认值
Optional<Author> author1 = Optional.ofNullable(author); Author author2 = author1.orElseGet(() -> new Author()); System.out.println(author2);
-
orElseThrow:获取数据,如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。
Optional<Author> author1 = Optional.ofNullable(author); try { Author aNull = author1.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("数据为 NULL")); System.out.println(aNull); } catch (Throwable e) { throw new RuntimeException(e); }
4.2.5过滤
-
我们可以使用filter方法对数据进行过滤,如果原来是有数据的,但是不符合判断,也会变成一个无数据的Optional对象
Optional<Author> authorOptional = Optional.ofNullable(author); Optional<Author> authorOptional1 = authorOptional.filter(author1 -> author1.getAge() > 18); authorOptional.ifPresent(author1 -> System.out.println(author1));
4.2.6 判断
-
Optional.isPresent() 判断数据是否存在,空则返回false,否则true,这种方式不是最好的,推荐使用Optional.ifPresent()
if (authorOptional.isPresent()) { System.out.println(author.getName()); }
-
Optional.ifPresent(),上面isPresent不能体现Optional的优点
Optional<Author> authorOptional = Optional.ofNullable(author); authorOptional.map(author1 -> author1.getBooks()).ifPresent( books -> System.out.println(books));
-
使用的时候可以先判断,相当于先判空,再去get,这样就不会空指针了
4.2.7 数据转换
-
Optional还提供map可以对数据进行转换,并且转换得到的数据还是Optional包装好的,保证安全使用
Optional<Author> authorOptional = Optional.ofNullable(author); Optional<List<Book>> optionalBooks = authorOptional.map(author1 -> author1.getBooks()); optionalBooks.ifPresent(books -> books.forEach(book -> System.out.println(book.getName())));
5. 函数式接口
- 只有一个抽象方法的接口就是函数式接口
- JDK的函数式接口都加上了@FunctionalInterface注解进行标识,但是无论加不加该注解,只要接口中只有一个抽象方法,都是函数式接口
- 常见的函数式接口
- Consumer 消费接口:可以对传入的参数进行消费
- Function 计算转换接口:根据其中抽象方法的参数列表和返回值类型可以看到,可以在方法中对传入的参数计算或转换,把结果返回
- Predicate 判断接口:可以在方法对传入的参数条件进行判断,返回判断结果
- Supplier 生产型接口:可以在方法中创建对象,把创建好的对象返回
- 常用的默认方法
- and :我们在使用Predicate接口的时候可能需要进行判断条件的拼接,而and方法相当于使用&&来拼接两个判断条件
// 打印作家中年龄大于17并且姓名的长度大于1的作家
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(new Consumer<Author>() {
@Override
public void accept(Author author) {
System.out.println(author.getName()+","+author.getAge());
}
});
- or : 我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用|来拼接两个判断条件。
// 打印作家中年龄大于17 或者姓名的长度小于2的作家
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17)
.or(author -> author.getName().length() > 2))
.forEach(author -> System.out.println(author.getName() + "," + author.getAge()));
- negate : Predicate接口中的方法。negate方法相当于是在判断添加前面加了个!表示取反
6. 方法引用
我们在使用lambda时,如果方法体中只有一个方法的调用的话(包括构造方法),我们可以用方法引用进一步简化代码。
6.1 推荐用法
我们在使用lambda时不需要考虑什么时候用方法引用,用哪种方法引用,方法引用的格式是什么。我们只需要在写完lambda方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可。
当我们方法引用使用的多了慢慢的也可以直接写出方法引用。
6.2 基本格式
类名或者对象名 :: 方法名
6.3 语法详解(了解)
6.3.1 引用静态方法
其实就是引用类的静态方法
格式
类名::方法名
使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法
authors.stream()
.map(author -> author.getAge())
.map(age -> String.valueOf(age));
注意,如果我们所重写的方法是没有参数的,调用的方法也是没有参数的也相当于符合以上规则。
优化后如下:
authors.stream()
.map(author -> author.getAge())
.map(String::valueOf);
6.3.2 引用对象的实例方法
格式
对象名:方法名
使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法
StringBuilder sb = new StringBuilder();
authors.stream()
.map(author -> author.getName())
.forEach(str -> sb.append(str));
优化后如下:
authors.stream()
.map(author -> author.getName())
.forEach(sb::append);
6.3.3 引用类的实例方法
格式
类名::方法名
使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了第一个参数的成员方法,并且我们把要重写的抽象方法中剩余的所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用类的实例方法
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);
}
6.3.4 构造器引用
如果方法体中的一行代码是构造器的话就可以使用构造器引用。
格式
类名::new
使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的构造方法,并且我们把要重写的抽象方法中的所有的参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器
authors.stream()
.map(Author::getName)
.map(StringBuilder::new)
.map(sb -> sb.append("AZ").toString())
.forEach(System.out::println);
7. 高级用法
基本数据类型优化
我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。
即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK 5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。
所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法。
例如: mapTolnt, mapToLong, mapToDouble, flatMapToInt, flatMapToDouble等。
authors.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.filter(age -> age > 18)
.map(age -> age + 2)
.forEach(System.out::println);
并行流
当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完全。如果我们自己去用代码实现的话其实会非常的复杂,并且要求你对并发编程有足够的理解和认识。而如果我们使用Stream的话,我们只需要修改一个方法的调用就可以使用并行流来帮我们实现,从而提高效率。
- parallel方法可以把串行流转换成并行流
- parallelStream直接获取并行流对象