1. 什么是stream
- stream被定义为泛型接口
- stream接口代表数据流
- stream不是一个数据结构,不直接存储数据
- stream通过管道操作数据
2. 什么是管道
- 管道包括:
1、数据集:可以是集合、数组等list 、array
2、过滤器filter
3、终端操作,如Stream.forEach方法
3. 什么是过滤器
- stream的过滤器可以匹配数据源,并返回一个stream对象。
Stream<Student> stream = list.stream();
stream = stream.filter(p->p.getSex=='男');
4. stream实战
- 创建Student实例
package com.fantJ.JAVA_8;
/**
* Created by Fant.J.
* 2017/12/12 21:46
*/
public class Student {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public Student(String name, String sex, int age) {
this.name = name;
this.age = age;
this.sex = sex;
}
}
- 创建Stream_Collection类
package com.fantJ.JAVA_8;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* Created by Fant.J.
* 2017/12/12 21:46
*/
public class Stream_Collection {
public static void main(String[] args) {
List<Student> list = init();
//获取stream对象
Stream<Student> stream = list.stream();
//遍历集合
stream.forEach(p-> System.out.println(p.toString()));
}
static List<Student> init(){
List<Student> list = new ArrayList<>();
Student student = new Student("老焦","男",1);
list.add(student);
student = new Student("老王","男",1);
list.add(student);
student = new Student("老赵","女",1);
list.add(student);
return list;
}
}
![img_e105c60918b440f6abd18e91117043d2.png](https://i-blog.csdnimg.cn/blog_migrate/d4a1e26147d8c95f4d5d3e6ccc880ff4.png)
stream.png
5. stream filter实战
稍微修改下Stream_Collection这个类的main方法如下,
List<Student> list = init();
//stream过滤器的实例
list.stream()
.filter(p->p.getSex()
.equals("女"))
.forEach(p-> System.out.println(p.toString()));
这个过滤器是实现对性别是“女”进行过滤并打印。
![img_0f1a7bcca12684082efe6933d36bd608.png](https://i-blog.csdnimg.cn/blog_migrate/8956cb0f3d486845185bc468216ebab0.png)
stream filter.png
6.进阶
![img_437ef93b071d842f7b8f1067dc7c56f7.png](https://i-blog.csdnimg.cn/blog_migrate/55d70cadc8341bec6532b78b80622f4a.png)
image.png
![img_38b7c37474e3c0f9f3133543ecebfe2a.png](https://i-blog.csdnimg.cn/blog_migrate/059c5249ae5e68b60e025323a31dbf3f.png)
image.png