stream流
3. Stream流
3.1 概述
Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。
3.2 案例数据准备
1 | <dependencies> |
1 |
|
1 | private static List<Author> getAuthors() { |
3.3 快速入门
3.3.1 需求
我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字,并且要注意去重。
3.3.2 实现
1 | //打印所有年龄小于18的作家的名字,并且要注意去重 |
3.4 常用操作
3.4.1 创建流
单列集合: 集合对象.stream()
1 | List<Author> authors = getAuthors(); |
数组:Arrays.stream(数组)或者使用Stream.of来创建1
2
3Integer[] arr = {1,2,3,4,5};
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream2 = Stream.of(arr);
双列集合:转换成单列集合后再创建1
2
3
4
5Map<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
可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
例如:
打印所有姓名长度大于1的作家的姓名
1 | List<Author> authors = getAuthors(); |
map
可以把对流中的元素进行计算或转换。
例如:
打印所有作家的姓名1
2
3
4
5
6List<Author> authors = getAuthors();
authors
.stream()
.map(author -> author.getName())
.forEach(name->System.out.println(name));
1 | // 打印所有作家的姓名 |
distinct
可以去除流中的重复元素。
例如:
打印所有作家的姓名,并且要求其中不能有重复元素。
1 | List<Author> authors = getAuthors(); |
注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。
sorted
可以对流中的元素进行排序。
例如:
对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
1 | List<Author> authors = getAuthors(); |
1 | List<Author> authors = getAuthors(); |
注意:如果调用空参的sorted()方法,需要流中的元素是实现了Comparable。
limit
可以设置流的最大长度,超出的部分将被抛弃。
例如:
对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。1
2
3
4
5
6List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted()
.limit(2)
.forEach(author -> System.out.println(author.getName()));
skip
跳过流中的前n个元素,返回剩下的元素
例如:
打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。1
2
3
4
5
6
7// 打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted()
.skip(1)
.forEach(author -> System.out.println(author.getName()));
flatMap
map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。
例一:
打印所有书籍的名字。要求对重复的元素进行去重。1
2
3
4
5
6
7// 打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.forEach(book -> System.out.println(book.getName()));
例二:
打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情1
2
3
4
5
6
7
8// 打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情 爱情
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.4.3 终结操作
forEach
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
例子:
输出所有作家的名字1
2
3
4
5
6
7// 输出所有作家的名字
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.distinct()
.forEach(name-> System.out.println(name));
count
可以用来获取当前流中元素的个数。
例子:
打印这些作家的所出书籍的数目,注意删除重复元素。1
2
3
4
5
6
7
8// 打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = getAuthors();
long count = authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
max&min
可以用来或者流中的最值。
例子:
分别获取这些作家的所出书籍的最高分和最低分并打印。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// 分别获取这些作家的所出书籍的最高分和最低分并打印。
//Stream<Author> -> Stream<Book> ->Stream<Integer> ->求值
List<Author> authors = getAuthors();
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((score1, score2) -> score1 - score2);
Optional<Integer> min = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.min((score1, score2) -> score1 - score2);
System.out.println(max.get());
System.out.println(min.get());
collect
把当前流转换成一个集合。
例子:
获取一个存放所有作者名字的List集合。1
2
3
4
5
6// 获取一个存放所有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> nameList = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toList());
System.out.println(nameList);
获取一个所有书名的Set集合。
1 | // 获取一个所有书名的Set集合。 |
获取一个Map集合,map的key为作者名,value为List<Book>
1 | // 获取一个Map集合,map的key为作者名,value为List<Book> |
查找与匹配
anyMatch
可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。
例子:
判断是否有年龄在29以上的作家1
2
3
4
5// 判断是否有年龄在29以上的作家
List<Author> authors = getAuthors();
boolean flag = authors.stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(flag);
allMatch
可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。
例子:
判断是否所有的作家都是成年人1
2
3
4
5// 判断是否所有的作家都是成年人
List<Author> authors = getAuthors();
boolean flag = authors.stream()
.allMatch(author -> author.getAge() >= 18);
System.out.println(flag);
findAny
获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。
例子:
获取任意一个年龄大于18的作家,如果存在就输出他的名字1
2
3
4
5
6
7// 获取任意一个年龄大于18的作家,如果存在就输出他的名字
List<Author> authors = getAuthors();
Optional<Author> optionalAuthor = authors.stream()
.filter(author -> author.getAge()>18)
.findAny();
optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
findFirst
获取流中的第一个元素。
例子:
获取一个年龄最小的作家,并输出他的姓名。1
2
3
4
5
6
7// 获取一个年龄最小的作家,并输出他的姓名。
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两个参数的重载形式内部的计算方式如下:
1 | T result = identity; |
其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。
例子:
使用reduce求所有作者年龄的和
1 | // 使用reduce求所有作者年龄的和 |
使用reduce求所有作者中年龄的最大值
1 | // 使用reduce求所有作者中年龄的最大值 |
使用reduce求所有作者中年龄的最小值
1 | // 使用reduce求所有作者中年龄的最小值 |
reduce一个参数的重载形式内部的计算
1 | boolean foundAny = false; |
如果用一个参数的重载方法去求最小值代码如下:
1 | // 使用reduce求所有作者中年龄的最小值 |
3.5 注意事项
- 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
- 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
- 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)




