一、Stream 流的简介
1.简介
Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对 集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。 使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数 据库查询。 也可以使用 Stream API 来并行执行操作。简而言之, Stream API 提供了一种高效且易于使用的处理数据的方式。
2.操作 stream 流的三个步骤
1.创建 stream 流对象。
常见的方式是通过数据源得到的。
2.中间操作
如:过滤,排序等
3.终止操作
一个终止操作触发中间操作,得到最终的结果
3.创建 stream 流
1.将集合转为 stream 流。
list.stream()
2.将数组转为 stream 流。
Student[] students = new Student[10];
students[0] = new Student();
Stream<Student> stream = Arrays.stream(students);
4.Stream 流的静态方法
获取无限流
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
例如:
Stream<Integer> stream = Stream.iterate(0, (x) -> x + 2);
stream.forEach(System.out::println);
public static<T> Stream<T>generate(Supplier<T> s)
例如:
Stream<Double> stream = Stream.generate(() -> Math.random());
stream.forEach(System.out::println);
5.Stream 流的中间操作
stream 流的中间操作
* filter 过滤 重点掌握
* limit 取值个数
* distinct 去重
* skip 跳过、
* map 映射 重点掌握
* sorted 排序 掌握
public class StreamDemo2 {
List<Student> list = Arrays.asList(
new Student(1,"zs",28,88.5),
new Student(2,"ls",24,89.5),
new Student(3,"ww",21,86.5),
new Student(4,"zl",19,98.5),
new Student(5,"tq",22,82.5),
new Student(6,"mb",21,83.5),
new Student(6,"mb",21,83.5)
);
5.1 filter 过滤
@Test
public void test1(){
Stream<Student> stream = list.stream()
.filter((s) ->{System.out.println("中间操作");return s.getAge() > 20;});
stream.forEach(System.out::println); // 终止操作
}
5.2 limit 限制取值个数
@Test
public void test2(){
list.stream()
.filter((s) ->{System.out.println("中间操作"); return s.getAge() > 20;})
.limit(2) // 短路操作 不会把所有的数据 都过滤 再取两条 ,而是 取两条满足条件的 剩下的短路
.forEach(System.out::println);
}
5.3 distinct 去重操作
@Test
public void test3(){
list.stream()
.filter((s) -> {return s.getAge() > 2;})
.distinct()//去重操作
.forEach(System.out::println);
}
5.4 skip 跳过操作
@Test
public void test4(){
list.stream()
.filter((s) -> {return s.getAge() > 20;})
.skip(2)
.forEach(System.out::println);
}
5.5 map 映射
@Test
public void test5(){
//map 映射
list .stream()
.filter((s)->s.getScore()>90)
//.map((s)-> s.getName())
.map(Student::getName)
.forEach(System.out::println);
}
5.5 sorted 排序
@Test
public void test6(){
//sorted 排序
list.stream()
.sorted() // 自然排序 按照流中元素的 比较规则来排序
.forEach(System.out::println);
}
@Test
public void test7(){
//sorted 排序
list.stream()
.sorted((s1,s2)->{return (s1.getScore()-s2.getScore())>0?1:-1;})
.forEach(System.out::println);
}
}
6.Stream 流的终止操作
// 查找 与 匹配 相关的终止操作
boolean b = list.stream().allMatch(s -> s.getScore() > 90);
boolean b = list.stream().anyMatch(s -> s.getScore() > 90);
boolean b = list.stream().noneMatch(s -> s.getScore() > 90);
allMatch // 都匹配
anyMatch // 任意一个匹配
noneMatch // 都不匹配
findFirst(); // 查找第一个
count(); //统计流中的元素个数