一、为什么要使用Stream?Stream是什么?在Java中该怎么用呢?
(1)为什么要使用Stream?
Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作 (bulk data operation)。Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。
(2) Stream是什么?
首先,Stream 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的,它更像一个高级版本的 Iterator。原始版本的 Iterator,用户只能显式地一个一个遍历元素并对其执行某些操作;高级版本的 Stream,用户只要给出需要对其包含的元素执行什么操作,比如 “过滤掉长度大于 10 的字符串”、“获取每个字符串的首字母”等,Stream 会隐式地在内部进行遍历,做出相应的数据转换。
Stream 就如同一个迭代器(Iterator),单向,不可往复,数据只能遍历一次,遍历过一次后即用尽了,就好比流水从面前流过,一去不复返。
(3) Stream在Java中如何用呢?
当我们使用Stream流时,一般包含三个步骤:获取一个数据源(source)→ 数据转换 → 执行操作获取想要的结果,每次转换原有 Stream 对象不改变,返回一个新的 Stream 对象(可以有多次转换),这就允许对其操作可以像链条一样排列,变成一个管道。
有多种方式产生一个流:
① 从Collection和数组中产生一个流:Collection.stream() Collection.parallelStream()
Arrays.stream(T array) Stream.of(元素)
② 从BufferedReader中产生一个流: Collection.parallelStream()
二、详解流的使用:
(1) a . map的详解:map 生成的是个 1:1 映射,每个输入元素,都按照规则转换成为另外一个元素。还有一些场景,是一对多映射关系的,这时需要 flatMap。
例1:将数组中的字符串转为大写,求平方数
@Test
public void mapTest(){
//将数组的字符串转为大写
String[] wordList = new String[]{"Java","Android","OS","IOS"};
List<String> output = Arrays.stream(wordList).
map(String::toUpperCase).
collect(Collectors.toList());
System.out.println(output);
//平方数
List<Integer> nums = Arrays.asList(1,2,3,4);
List<Integer> squareNums = nums.stream().
map(n -> n * n).
collect(Collectors.toList());
System.out.println(squareNums);
}
注意:map(String::toUpperCase)这样的写法,这就是我们上篇博客讲的Lambda表达式的方法引用!诶,大家会不会觉得toUpperCase()这个方法不是String类中的静态方法,为啥可以这样调用呢?
map((str) -> str.toUpperCase()) 还原之前的Lambda表达式,toUpperCase()是String的成员方法,但是str会作为参数原封不动的传递给表达式str.toUpperCase(),这样就可以使用String::toUpperCase改写。
map(personal :: getName).collect(Collectors.toList) 此方法将获取该集合中对象某值产生的新集合。
b . flatMap : 将多个Stream合并为一个Stream。惰性求值
public class TestCase {
public static void main(String[] args) {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
List<Student> studentList = Stream.of(students,
asList(new Student("艾斯", 25, 183),
new Student("雷利", 48, 176)))
.flatMap(students1 -> students1.stream()).collect(Collectors.toList());
System.out.println(studentList);
}
}
//输出结果
//[Student{name='路飞', age=22, stature=175, specialities=null},
//Student{name='红发', age=40, stature=180, specialities=null},
//Student{name='白胡子', age=50, stature=185, specialities=null},
//Student{name='艾斯', age=25, stature=183, specialities=null},
//Student{name='雷利', age=48, stature=176, specialities=null}]
调用Stream.of的静态方法将两个list转换为Stream,再通过flatMap将两个流合并为一个。
(2) filter 的详解:filter对原始 Stream 进行某项测试,通过测试的元素被留下来生成一个新 Stream。
例2:过滤数组中的奇数,留下偶数
@Test
public void filterTest(){
//留下偶数
Integer[] nums = {1,2,3,4,5,6};
Integer[] evens = Stream.of(nums).
filter(n -> n%2 == 0).
toArray(Integer[]::new);
for (Integer even : evens) {
System.out.println(even);
}
}
例3:将文件中的单词挑出,转为小写,排序并保证不重复
@Test
public void testDistinct() {
try {
//
BufferedReader br = new BufferedReader(new FileReader("src/main/resource/test.txt"));
//获取不重复的单词集合
List<String> wordList = br.lines().
flatMap(line -> Stream.of(line.split(" "))).
filter(word -> word.length() > 0).
map(String::toLowerCase).
distinct().
sorted().
collect(Collectors.toList());
System.out.println(wordList);
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
(3) reduce的详解:这个方法的主要作用是把 Stream 元素组合起来。它提供一个起始值(种子),然后依照运算规则(BinaryOperator),和前面 Stream 的第一个、第二个、第 n 个元素组合。从这个意义上说,字符串拼接、数值的 sum、min、max、average 都是特殊的 reduce。
例4:字符串拼接,求最小值、最大值、过滤字符串拼接
@Test
public void reduce(){
//字符串连接
String concat1 = Stream.of("A","B","C","D").reduce("", (x,y) -> x.concat(y));
String concat2= Stream.of("A","B","C","D").reduce("", String::concat);
System.out.println(concat1 + concat2);
//求最小值
double minValue1 = Stream.of(-1.5,1.0,-3.0,-2.0).reduce(Double.MAX_VALUE, (x,y) -> Double.min(x, y));
double minValue2 = Stream.of(-1.5,1.0,-3.0,-2.0).reduce(Double.MAX_VALUE, Double::min);
System.out.println(minValue1);
System.out.println(minValue2);
//求最和
int sumValue1 = Stream.of(1,2,3,4).reduce(0, (x,y) -> x + y);
//原因:Integer类中的sum()方法完全可以替代两个数求和,参数类型、个数、返回值相同
int sumValue2 = Stream.of(1,2,3,4).reduce(0, Integer::sum);
System.out.println(sumValue1);
System.out.println(sumValue2);
//过滤字符串并拼接
String concat = Stream.of("a","D","c","B","C","A").
filter(s -> s.compareTo("Z") > 0).
reduce("", String::concat);
System.out.println(concat);
}
(4) limit/skip的详解:limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素。
例5:留下数组中的偶数,并扔掉前4 个元素。
@Test
public void testLimitAndSkip() {
List<Integer> list = new ArrayList();
for (int i = 1; i <= 20; i++) {
list.add(i);
}
//limit()返回前n个元素,skip则是扔掉前n个元素
List<Integer> list1 = list.stream().
filter(x -> x % 2 == 0).limit(10).skip(4).collect(Collectors.toList());
System.out.println(list1);
}
(5) sorted的详解:对 Stream 的排序通过 sorted 进行,它比数组的排序更强之处在于你可以首先对 Stream 进行各类 map、filter、limit、skip 甚至 distinct 来减少元素数量后,再排序,这能帮助程序明显缩短执行时间。
@Test
public void testLimitAndSkip1() {
Integer[] arr = new Integer[]{2,5,3,4,7,8,5,12,13,16,18,19,20};
List<Integer> list = Arrays.asList(arr);
//limit()返回前n个元素,skip则是扔掉前n个元素
List<Integer> list1 = list.stream().
sorted(). //先排序,从I小到大输出
filter(x -> x % 2 == 0).
limit(10).
skip(3).
collect(Collectors.toList());
System.out.println(list1);
}
(6) max/min/distinct的详解:保证Stream流集合中元素不重复,找出最大值、最小值等
@Test
public void testMax() {
Integer[] arr = new Integer[]{2,5,3,4,7,8,5,12,13,16,18,19,20};
List<Integer> list = Arrays.asList(arr);
//求最大值
Integer maxValue = list.stream().
max(Integer::compareTo).get();
System.out.println(maxValue);
//求最小值
Integer minValue = list.stream().
min(Integer::compareTo).get();
System.out.println(minValue);
}
(7) Stream中List、Set、Map之间的转换操作:
新建一个Course类,包含name、credit两个属性,并重写hashCode()、equals()方法:
class Course {
private String name;
private Integer credit;
public Course(String name, Integer credit) {
this.name = name;
this.credit = credit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCredit() {
return credit;
}
public void setCredit(Integer credit) {
this.credit = credit;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
Course stu = null;
if (obj != null && obj instanceof Course) {
stu = (Course) obj;
if (this.name.equals(stu.getName()) && this.credit.equals(stu.getCredit())) {
return true;
}
}
return false;
}
}
(8) Stream中anyMatch和allMatch以及noneMatch操作:
- boolean anyMatch(Predicate<? super T> predicate) 只要有一个条件满足即返回true
- boolean allMatch(Predicate<? super T> predicate) 必须全部都满足才会返回true
- boolean noneMatch(Predicate<? super T> predicate) 全都不满足才会返回true
List<String> strs = Arrays.asList("a", "a", "a", "a", "b");
boolean aa = strs.stream().anyMatch(str -> str.equals("a"));
boolean bb = strs.stream().allMatch(str -> str.equals("a"));
boolean cc = strs.stream().noneMatch(str -> str.equals("a"));
long count = strs.stream().filter(str -> str.equals("a")).count();
System.out.println(aa);// TRUE
System.out.println(bb);// FALSE
System.out.println(cc);// FALSE
System.out.println(count);// 4
通过例子可以看到,变量aa的表达式,strs里的元素,任意有“a”,表示true
变量bb的表达式,strs里的元素,全部为“a”,表示true,否则false
变量cc的表达式,strs里的元素,全部不为“a”,表示true,否则false
- Stream将List转换为Map集合
/**
* Stream将List转换为Map集合
*/
@Test
public void listToMap() {
List<Course> stuList = Arrays.asList(
new Course("Android", 10),
new Course("Java", 8),
new Course("Structure", 13),
new Course("IOS", 12),
new Course("Guava", 16),
new Course("OS", 6));
Map<String, Integer> nameAgeMap = stuList.stream().
collect(Collectors.toMap(Course::getName, Course::getCredit));
nameAgeMap.entrySet().stream().forEach(x -> System.out.println(x.getKey() + ", " + x.getValue()));
//Function.identity()指代本身,相当于 x -> x
Map<String, Course> nameStuMap = stuList.stream().
collect(Collectors.toMap(Course::getName, Function.identity()));
nameStuMap.entrySet().stream().forEach(x -> System.out.println(x.getKey() + "," + x.getValue().getCredit()));
}
执行结果展示:(两次结果展示一致)
Guava, 16
Java, 8
OS, 6
IOS, 12
Structure, 13
Android, 10
注意:collect(Collectors.toMap(Course::getName,Function.identity())) 得到的是<name,course>Map集合。
查看Function.identity()底层实现原理:t -> t 返回对象本身
static <T> Function<T, T> identity() {
return t -> t;
}
-
Stream将List转换为Set集合
@Test
public void listToSet() {
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);
Set<Integer> integerSet = integerList.stream().
collect(Collectors.toSet());
integerSet.stream().forEach(System.out::print);
System.out.println("");
List<Course> courseList = Arrays.asList(
new Course("Android", 10),
new Course("Java", 8),
new Course("Android", 10),
new Course("IOS", 12),
new Course("Guava", 16),
new Course("Android", 6));
//排序并去重
List<Course> courList = courseList.stream().
sorted(Comparator.comparing(Course::getName)).
distinct().
collect(Collectors.toList());
courList.stream().forEach(c -> System.out.println(c.getName() + "," + c.getCredit()));
//只去重Set
Set<Course> courSet = courseList.stream().
sorted(Comparator.comparing(Course::getName)).
collect(Collectors.toSet());
courSet.stream().forEach(c -> System.out.println(c.getName() + "," + c.getCredit()));
}
结果展示:
12345
Android,10
Android,6
Guava,16
IOS,12
Java,8
Guava,16
Java,8
IOS,12
Android,10
Android,6
注意:对象去重需要重写类的hashCode()、equals()方法,给出去重排序、去重的List转换为Set集合。
高级集合类及收集器
3.1 转换成值
收集器,一种通用的、从流生成复杂值的结构。只要将它传给 collect 方法,所有的流就都可以使用它了。标准类库已经提供了一些有用的收集器,以下示例代码中的收集器都是从 java.util.stream.Collectors 类中静态导入的。
public class CollectorsTest {
public static void main(String[] args) {
List<Student> students1 = new ArrayList<>(3);
students1.add(new Student("路飞", 23, 175));
students1.add(new Student("红发", 40, 180));
students1.add(new Student("白胡子", 50, 185));
OutstandingClass ostClass1 = new OutstandingClass("一班", students1);
//复制students1,并移除一个学生
List<Student> students2 = new ArrayList<>(students1);
students2.remove(1);
OutstandingClass ostClass2 = new OutstandingClass("二班", students2);
//将ostClass1、ostClass2转换为Stream
Stream<OutstandingClass> classStream = Stream.of(ostClass1, ostClass2);
OutstandingClass outstandingClass = biggestGroup(classStream);
System.out.println("人数最多的班级是:" + outstandingClass.getName());
System.out.println("一班平均年龄是:" + averageNumberOfStudent(students1));
}
/**
* 获取人数最多的班级
*/
private static OutstandingClass biggestGroup(Stream<OutstandingClass> outstandingClasses) {
return outstandingClasses.collect(
maxBy(comparing(ostClass -> ostClass.getStudents().size())))
.orElseGet(OutstandingClass::new);
}
/**
* 计算平均年龄
*/
private static double averageNumberOfStudent(List<Student> students) {
return students.stream().collect(averagingInt(Student::getAge));
}
}
//输出结果
//人数最多的班级是:一班
//一班平均年龄是:37.666666666666664
maxBy或者minBy就是求最大值与最小值。
3.2 转换成块
常用的流操作是将其分解成两个集合,Collectors.partitioningBy帮我们实现了,接收一个Predicate函数式接口。
将示例学生分为会唱歌与不会唱歌的两个集合。
public class PartitioningByTest {
public static void main(String[] args) {
//省略List<student> students的初始化
Map<Boolean, List<Student>> listMap = students.stream().collect(
Collectors.partitioningBy(student -> student.getSpecialities().
contains(SpecialityEnum.SING)));
}
}
3.3 数据分组
数据分组是一种更自然的分割数据操作,与将数据分成 ture 和 false 两部分不同,可以使用任意值对数据分组。Collectors.groupingBy接收一个Function做转换。
如图,我们使用groupingBy将根据进行分组为圆形一组,三角形一组,正方形一组。
例子:根据学生第一个特长进行分组
public class GroupingByTest {
public static void main(String[] args) {
//省略List<student> students的初始化
Map<SpecialityEnum, List<Student>> listMap =
students.stream().collect(
Collectors.groupingBy(student -> student.getSpecialities().get(0)));
}
}
Collectors.groupingBy与SQL 中的 group by 操作是一样的。
3.4 字符串拼接
如果将所有学生的名字拼接起来,怎么做呢?通常只能创建一个StringBuilder,循环拼接。使用Stream,使用Collectors.joining()简单容易。
public class JoiningTest {
public static void main(String[] args) {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
String names = students.stream()
.map(Student::getName).collect(Collectors.joining(",","[","]"));
System.out.println(names);
}
}
//输出结果
//[路飞,红发,白胡子]
joining接收三个参数,第一个是分界符,第二个是前缀符,第三个是结束符。也可以不传入参数Collectors.joining(),这样就是直接拼接。
三、Stream总结:
(1) Stream不是数据结构;
(2) 它没有内部存储,它只是用操作管道从 source(数据结构、数组、generator function、IO channel)抓取数据;
(3) 它也绝不修改自己所封装的底层数据结构的数据。例如 Stream 的 filter 操作会产生一个不包含被过滤元素的新 Stream,而不是从 source 删除那些元素;
(4) 所有 Stream 的操作必须以 lambda 表达式为参数;
(5) 不支持索引访问;使用forEach()遍历数组,不可使用break,continue等关键字跳出循环;
(6) 你可以请求第一个元素findFirst(),但无法请求第二个,第三个,或最后一个。不过请参阅下一项。
(7) 很容易生成数组或者 List。