一、概述
很多兄弟,初入职场,在阅读公司代码的时候,发现公司代码里很多都用到了Stream流,可以说是非常频繁!所以学习Stream流就变得非常有必要。
这不仅可以帮助我们看懂公司同事写的代码,也可以高效地帮助我们完成一些需求,例如:集合元素的去重,转换,计算…提高代码的可读性,从而减少程序员之间的沟通成本,提高工作效率!
1.1 为什么学?
- 能够看懂公司的代码
- 大数量下处理集合效率高
- 代码可读性高
- 消灭嵌套地狱
//查询未成年作家的评分在70以上的书籍 , 作家和书籍可能出现重复, 需要进行去重
List<Book> bookList = new ArrayList<>()
Set<Book> uniqueBookValues = new HashSet<>
Set<Author> uniqueAuthorValues = new HashSet<)
for (Author author : authors) {
if(uniqueAuthorValues.add(author)) {
if (author.getAge() < 18) {
List<Book> books = author.getBooks();
for (Book book : books) {
if(book.getScore() > 70) {
if(uniqueBookValues.add(book)) {
bookList.add(book);
}
}
}
}
}
}
System.out.println(bookList);
List<Book> collect = authors.stream()
.distinct()
.filter(author -> author.getAge() < 18)
.map(author -> author.getBooks())
.flatMap(Collection::stream)
.filter(book -> book.getScore() > 70)
.distinct()
.collect(Collection.toList());
System.out.println(collect);
1.2 函数式编程思想
1.2.1 概念
面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。
1.2.2 优点
- 代码简洁,开发快速;
- 接近自然语言,易于理解;
- 易于“并发编程”;
二、Lambda 表达式
2.1 概述
Lambda是 JDK8 中一个语法糖。可以看成是一种语法糖,他可以从对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。
2.2 核心原则
可推导可省略
2.3 基本格式
(参数列表)->{代码}
- 例一:我们在创建线程并启动时可以使用匿名内部类的写法
new Thread(new Runnable(){
@Override
public void run() {
System.out.println("哈哈哈");
}
}).start();
可以使用Lambda的格式对其进行修改。修改后如下:
new Thread(() -> {
System.out.println("哈哈哈");
}).start();
2.4 省略规则
- 参数类型可以省略
- 方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
- 方法只有一个参数时小括号可以省略
- 以上这些规则都记不住也可以省略不记
三、Stream流
3.1 概述
Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式操作。可以更方便的对集合或数组操作。
3.2 案例数据准备
@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
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Book {
//id
private Long id;
//书名
private String name;
//分类
private String category;
//评分
private Integer score;
//简介
private String intro;
}
public class StreamDemo {
public static void main(String[] args) {
}
public static List<Author> getAuthors() {
//数据初始化
Author author1 = new Author(1L, "莫言", 69, "中国首位诺贝尔文学奖获得者", null);
Author author2 = new Author(2L, "韩寒", 41, "中国80后代表作家", null);
Author author3 = new Author(3L, "贾平凹", 72, "茅盾文学奖获得者", null);
Author author4 = new Author(3L, "贾平凹", 72, "茅盾文学奖获得者", 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, "秦腔发生的故事"));
author1.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3);
List<Author> authorList = new ArrayList<>(Arrays.asList(author1, author2, author3, author4));
return authorList;
}
}
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
3.3 快速入门
3.3.1 需求
我们可以调用getAuthors()方法获取到作家的集合。现在需要打印所有年龄小于70的作家的名字, 并且要注意去重。
3.3.2 实现
public class StreamDemo {
public static void main(String[] args) {
//打印所有年龄小于70的作家的名字, 并且要注意去重。
List<Author> authors = getAuthors();
authors.stream() //把集合转换成流
.distinct() //先去除重复的作家
.filter(author -> author.getAge() < 70) //筛选年龄小于70的作家
.forEach(author -> System.out.println(author.getName()));//遍历打印姓名
}
}
3.4 常用操作
3.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>> stream = map.entrySet().stream();
3.4.2 中间操作
① filter 过滤
可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
- 例如: 打印所有姓名长度大于2的作家的姓名。
List<Author>authors = getAuthors();
authors.stream()
.filter(author -> author.getName().length() > 2)
.forEach(author -> System.out.println(author.getName()));
② map 计算或转换
可以对流中的元素进行计算和转换。
- 例如:打印所有作家的姓名。
List<Author>authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.forEach(name -> System.out.println(name));
- 例如:对所有作家的年龄+10 并输出
// 对所有作家的年龄+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()方法:
// 首先让Author实现 Comparable 接口,并重写compareTo 方法
public class Author implements Comparable<Author>{
@Override
public int compareTo(Author o) {
return o.getAge() - this.getAge();
}
}
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted()
.forEach(author -> System.out.println(author.getAge()));
注意:使用 默认的sorted()方法 一定要让类实现Comparable接口并实现方法!
返回由该流的元素组成的流,按自然顺序排序。如果此流的元素不是Comparable,则在执行终端操作时可能会抛出 java.lang.ClassCastException
- 使用有参数的sorted( Comparator ) 方法:
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted((o1, o2) -> o2.getAge() - o1.getAge())
.forEach(author -> System.out.println(author.getAge()));
⑤ limit 限制
可以设置流的最大长度,超出的部分将被抛弃。
- 例如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。
List<Author> authors = getAuthors();
authors.stream()
.distinct() //去重
.sorted((o1, o2) -> o2.getAge() - o1.getAge()) //按照年龄降序排序
.limit(2) //限制为2
.forEach(author -> System.out.println(author.getName()));
⑥ skip 跳过
跳过流中的前n个元素,返回剩下的元素。
- 例如:打印除了年龄最大的作家外的其他作家姓名,要求不能有重复元素,并且按照年龄降序排序。
List<Author> authors = getAuthors();
authors.stream()
.distinct() //去重
.sorted((o1, o2) -> o2.getAge() - o1.getAge()) //按照年龄降序排序
.skip(1) //跳过前1个
.forEach(author -> System.out.println(author.getName()));
⑦ flatMap 转换成多个对象
map 只能把一个对象转换成另一个对象来作为流中的元素。而 flatMap 可以把一个对象转换成多个对象作为流中的元素。
- 例一:打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream()) //转换成 多个book对象
.distinct() //去重
.forEach(book -> System.out.println(book.getName()));
- 例二:打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式: 哲学,爱情
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream()) //转换为book
.distinct() //对书籍去重
.map(Book::getCategory) //转换为category
.flatMap(category -> Arrays.stream(category.split(","))) //分类颗粒化
.distinct() //对分类去重
.forEach(System.out::println);
3.4.3 终结操作
① forEach 遍历
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
- 例子:输出所有作家的名字。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.forEach(author -> System.out.println(author.getName()));
② count 个数
可以用来获取当前流中元素的个数。
- 例子:打印这些作家的所出书籍的数目,注意删除重复元素。
//打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = getAuthors();
long count = authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println("count = " + count);
③ max && min 最值
可以用来或者流中的 最值 。
- 例子:分别获取这些作家的所出书籍的最高分和最低分并打印。
//分别获取这些作家的所出书籍的最高分和最低分并打印。
List<Author> authors = getAuthors();
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(Book::getScore)
.max((o1, o2) -> o1 - o2);
System.out.println(max.get());
Optional<Integer> min = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(Book::getScore)
.max((o1, o2) -> o2 - o1);
System.out.println(min.get());
④ collect 集合
把当前流转换成一个集合。
- 例一:获取一个存放所有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> nameList = authors.stream()
.map(Author::getName)
.distinct()
.collect(Collectors.toList());
- 例二:获取一个所有书名的Set集合
//获取一个所有书名的Set集合
List<Author> authors = getAuthors();
Set<String> bookNameSet = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(Book::getName)
.collect(Collectors.toSet());
- 例三:获取一个map集合,map的key为作者名,value为List
List<Author> authors = getAuthors();
Map<String, List<Book>> authorMap = authors.stream()
.distinct()
.collect(Collectors.toMap(Author::getName, Author::getBooks));
⑤ 查找与匹配
anyMatch 任意符合
可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型
- 例子:判断是否有年龄在55以上的作家
List<Author> authors = getAuthors();
boolean match = authors.stream()
.distinct()
.anyMatch(author -> author.getAge() > 55);
System.out.println(match); //true
allMatch 都符合
可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。
- 例子:判断是否所有的作家都是成年人
List<Author> authors = getAuthors();
boolean match = authors.stream()
.distinct()
.allMatch(author -> author.getAge() > 18);
System.out.println(match); //true
noneMatch 都不符合
可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false
- 例子:判断作家是否都没有超过100岁的。
List<Author> authors = getAuthors();
boolean match = authors.stream()
.distinct()
.noneMatch(author -> author.getAge() > 100);
System.out.println(match); //true
findAny 获取任一
获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。
- 例子:获取任意一个年龄大于55的作家,如果存在就输出他的名字
List<Author> authors = getAuthors();
Optional<Author> optionalAuthor = authors.stream()
.distinct()
.filter(author -> author.getAge() > 55)
.findAny();
optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
findFirst 获取第一个
获取流中的第一个元素。
- 例子:获取最小年龄的作家,并输出他的名字
List<Author> authors = getAuthors();
Optional<Author> optionalAuthor = authors.stream()
.sorted((Comparator.comparingInt(Author::getAge)))
.findFirst();
optionalAuthor.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;
其中identity就是我们可以通过方法参数传入的初始值,accumulatorr的apply具体进行什么计算也是我们通过方法参数来确定的。
- 例一:使用reduce求所有作者年龄的和
List<Author> authors = getAuthors();
Integer sum = authors.stream()
.distinct()
.map(Author::getAge)
.reduce(0, Integer::sum);
System.out.println("sum = " + sum);
- 例二:使用reduce求所有作者中年龄的最大值
List<Author> authors = getAuthors();
Integer maxAge = authors.stream()
.map(Author::getAge)
.reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
System.out.println("maxAge = " + maxAge);
- 例三:使用 reduce 求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Integer minAge = authors.stream()
.map(Author::getAge)
.reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
System.out.println("minAge = " + 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的一个参数的重载形式,求所有作者中年龄的最大值
List<Author> authors = getAuthors();
Optional<Integer> maxAge = authors.stream()
.distinct()
.map(Author::getAge)
.reduce((result, element) -> result < element ? element : result);
maxAge.ifPresent(System.out::println);
⑦ concat 延迟串联
concat() Java中Stream类的方法创建一个延迟串联的流,其元素是第一个流的所有元素,然后是第二个流的所有元素。语法如下:
concat(Stream<? extends T> a, Stream<? extends T> b)
这里,a是第一流,而b是第二流。T是流元素的类型。
- 例一:
以下是实现concat()Stream类的方法的示例:
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> streamOne = Stream.of("John");
Stream<String> streamTwo = Stream.of("Tom");
Stream.concat(streamOne, streamTwo).forEach(val -> System.out.println(val));
}
}
输出结果:
John
Tom
- 例二:
现在让我们看看另一个示例,其中我们正在处理多个流
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Stream.*;
public class Main {
public static void main(String[] args) {
Stream<Integer> streamOne = Stream.of(15, 40, 50);
Stream<Integer> streamTwo = Stream.of(55, 70, 90);
Stream<Integer> streamThree = Stream.of(110, 130, 150);
Stream<Integer> streamFour = Stream.of(170, 200, 240, 300);
Stream<Integer> res = Stream.concat(streamOne, concat(streamTwo, concat(streamThree, streamFour)));
System.out.println( res.collect(Collectors.toList()) );
}
}
输出结果:
[15, 40, 50, 55, 70, 90, 110, 130, 150, 170, 200, 240, 300]
3.5 注意事项
- 惰性求值 (如果没有终结操作,没有中间操作是不会得到执行的)
- 流是一次性的 (一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
- 不会影响原数据 (我们在流中可以对数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)
四、Optional
4.1 概述
我们在编写代码的时候出现最多的就是 空指针异常。所以在很多情况下我们需要做各种非空的判断。
例如:
Author author = getAuthor();
if(author != null) {
System.out.println(author.getName());
}
尤其是对象中的属性还是一个对象的情况下。这种判断会更多。
而过多的判断语句会让我们的代码显得 臃肿不堪。
所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免 空指针异常。
并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。
4.2 使用
4.2.1 创建对象
Optional就好像是包装类,可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据,就可以非常优雅的避免 空指针异常。
我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题。
Author author=getAuthor();
Optional<Author> authorOptional = Opticonal.ofNullable(author)
authorOptional.ifPresent(author1 -> System.out.println(author1.getName()));
你可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下getAuthor方法,让其的返回值就是封装好的Optional的话,我们在使用时就会方便很多。
而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。
如果你确定一个对象不是空的则可以使用Optional的静态方法of来把数据封装成Optional对象。
Author author=new Author();
Optional<Author> authorOptional = Optional.of(author);
但是一定要注意,如果使用of的时候传入的参数必须不为null。(尝试下传入null会出现什么结果)
如果一个方法的返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional的静态方法empty来进行封装。
Optional.empty();
所以最后你觉得哪种方式会更方便呢?
4.2.2 安全消费值
我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值。
这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。
例如,以下写法就优雅的避免了 空指针异常。
Optional<Author> authorOptional = Optional.ofNu1lable(getAuthor());
authoroptional.ifPresent(author -> System.out.println(author.getName()));
4.2.3 获取值
如果我们想获取值自己进行处理可以使用get方法获取,但是不推荐。因为当Optional内部的数据为空的时候会出现异常。
4.2.4 安全获取值
如果我们期望安全的获取值。我们不推荐使用get方法,而是使用Optional提供的以下方法。
- orElseGet
获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回。
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
Author author = authorOptional.orElseGet(Author::new);
- orElseThrow
获取数据,如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
try{
Author author = authorOptional.orElseThrow(() -> new RuntimeException("author为空"));
System.out.println(author.getName());
}catch (Throwable throwable) {
throwable.printStackTrace();
}
4.2.5 过滤
我们可以使用filter方法对数据进行过滤。如果原本是有数据的,但是不符合判断,也会变成一个无数据的Optional对象。
Optional<Author> authorsOptional = Optional.ofNullable(getAuthor());
authorsOptional.filter(author -> author.getAge() > 66)
.ifPresent(author -> System.out.println(author.getName()));
4.2.6 判断
我们可以使用isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空,返回值为true。但是这种方式并不能体现Optional的好处,更推荐使用ifPresent方法。
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
if (authoroptional.isPresent()) {
System.out.printin(authorOptional.get().getName())
}
4.2.7 数据转换
Optional还提供了map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全。
例如我们想获取作家的书籍集合。
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
Optional<List<Book>> books = authoroptional.map((author -> author.getBooks());
books.ifPresent(new Consumer<List<Book>>(){
@override
public void accept(List<Book> books) {
books.forEach(book -> System.out.printin(book.getName)));
}
});
五、函数式接口
5.1 概述
只有一个抽象方法的接口我们称之为函数接口。
JDK的函数式接口都加上了@FunctionalInterface注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是 函数式接口。
5.2 常见的函数式接口
① Comsumer 消费接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费。
@FunctionalInterface
public interface Comsumer<T> {
/**
* Perform this operation on the given argument.
*
* @param t the input argument
*/
void accept(T 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);
}
③ Predicate 判断接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果。
@FunctionalInterface
public interface Predicate {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matchs the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
④ Supplier 生产型接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回。
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
5.3 默认的常用方法
① and
我们在使用Predicate接口的时候可能需要进行判断条件的拼接。而 and 方法相当于是使用&&来拼接两个判断条件。
- 例如:打印作家中年龄大于66 并且 姓名的长度大于2 的作家。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.filter(((Predicate<Author>) author -> author.getAge() > 66)
.and(author -> author.getName().length() > 2))
.forEach(System.out::println);
② or
我们在使用Predicate接口的时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。
- 例如:打印作家中年龄大于66 或者 姓名的长度小于2 的作家。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.filter(((Predicate<Author>) author -> author.getAge() > 66)
.or(author -> author.getName().length() < 2))
.forEach(System.out::println);
③ negate
Predicate接口中的方法。negate方法相当于是在判断添加前面加了个! 表示取反。
- 例如:打印作家中年龄不大于66的作家。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.filter(((Predicate<Author>) author -> author.getAge() > 66).negate())
.forEach(System.out::println);
六、方法引用
我们在使用Lambda时,如果方法体中只有一个方法的调用的话(包括构造方法),我们可以用方法引用进一步简化代码。
6.1 推荐用法
我们在使用Lambda时不需要考虑什么时候用方法引用,用哪种方法引用,方法引用的格式是什么。我们只需要在写完Lambda方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可。
当我们方法引用使用的多了慢慢的也可以直接写出方法引用。
6.2 基本格式
类名或者对象名::方法名
6.3 语法详情(了解)
6.3.1 引用静态方法
其实就是引用类的静态方法
- 格式:
类名::方法名 - 使用前提:
如果我们在重写方法的时候,方法体只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中的所有参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。 - 例如: 如下代码就可以用方法引用进行简化
List<Author>authors = getAuthors();
authors.stream()
.distinct()
.map(author -> author.getAge())
.map(age -> String.valueOf(age))
.forEach(s -> System.out.println(s));
注意,如果我们所重写的方法是没有参数的,调用的方法也是没有参数的也相当于符合以上规则。
- 优化后如下:
List<Author>authors = getAuthors();
authors.stream()
.distinct()
.map(Author::getAge)
.map(String::valueOf)
.forEach(System.out::println);
6.3.2 引用对象的实例方法
- 格式:
对象名::方法名 - 使用前提:
如果我们在重写方法的时候,方法体只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中的所有参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法。 - 例如: 如下代码就可以用方法引用进行简化
List<Author> authors = getAuthors();
StringBuilder sb = new StringBuilder();
authors.stream()
.distinct()
.map(author -> author.getName())
.forEach(name -> sb.append(name));
System.out.println(sb);
- 优化后如下:
List<Author> authors = getAuthors();
StringBuilder sb = new StringBuilder();
authors.stream()
.distinct()
.map(Author::getName)
.forEach(sb::append);
System.out.println(sb);
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) {
String s = subAuthorName("帅哥草堂", (str, start, length) -> str.substring(start, length));
System.out.println(s);
}
- 优化后如下:
public static void main(String[] args) {
String s = subAuthorName("帅哥草堂", String::substring);
System.out.println(s);// 帅
}
6.3.4 构造器引用
如果方法体中的一行代码是构造器的话就可以使用构造器引用。
- 格式:
类名::new - 例如:
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.map(author -> author.getName())
.map(name -> new StringBuilder(name))
.map(sb -> sb.toString())
.forEach(s -> System.out.println(s));
- 优化后如下:
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.map(Author::getName)
.map(StringBuilder::new)
.map(StringBuilder::toString)
.forEach(System.out::println);
七、高级用法
基本数据类型优化
我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。
即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要要消耗时间的。虽然这个时间消耗很小。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。
所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法。
例如:mapToInt,mapToLong,mapToDouble,flatMapToInt,flatMapToDouble等。
- 优化前:
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.map(Author::getAge)
.map(age -> age + 10)
.filter(age -> age > 78)
.map(age -> age + 2)
.forEach(System.out::println);
- 优化后:
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.mapToInt(Author::getAge)
.map(age -> age + 10)
.filter(age -> age > 78)
.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 sum = stream.parallel()
.peek(new Consumer<Integer>(){
@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(sum);
- 也可以通过 parallelStream 直接获取并行流对象
List<Author> authors = getAuthors();
authors.parallelStream()
.map(author -> author.gerAge())
.map(age -> age + 10)
.filter(age -> age > 66)
.forEach(System.out::println);

3990





