Stream
Stream 是Java8中处理集合的关键抽象概念,它可以对集合进行非常复杂的查找、过滤、筛选等操作.

Stream操作还有两个基础的特征:
Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。
内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。
Stream流的创建
每个Stream流只能使用一次
双冒号运算就是 java 中的[方法引用]。 [方法引用]格式为:类名::方法名。
中间操作都会返回流对象本身,也就是说可以一直.方法名
- list创建流
List<String> list = Lists.newArrayList("A", "B", "C");
Stream<String> stream1 = list.stream();
- 数组创建流
String[] arr = {"A", "B"};
Stream<String> stream2 = Arrays.stream(arr);
- iterate方法创建流
// iterate会无限执行,所以limit只取前4个
Stream<Integer> stream4 = Stream.iterate(0, x -> x * x).limit(4);
- generate方法创建流
// generate也会无限执行,所以limit只取前4个
Stream<Double> stream5 = Stream.generate(Math::random).limit(4);
一般list.stream()用的比较多
Stream API
- filter()
// 过滤
list.stream().filter(x -> x.contains("b")).forEach(System.out::println);
filter()方法的参数是过滤条件(true或者false),可以跟lambda表达式
- limit(n)
// 取前n
list.stream().limit(1).forEach(System.out::println);
- skip(n)
// 跳过前n个
list.stream().skip(2).forEach(System.out::println);
- distinct()
list.stream().distinct().forEach(System.out::println);
- map()
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
- sorted()
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
- peek()
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);
studentList.stream()
.peek(o -> o.setAge(100))
.forEach(System.out::println);
//结果:
Student{name='aa', age=100}
Student{name='bb', age=100}
peek:如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值。
- collect()
//collect--> 将stream转成list集合
List<Integer> collect = list1.stream().map(x -> x * 2).collect(Collectors.toList());
collect.forEach(System.out::println);
- reduce()
//归约
Optional<Integer> reduce = list1.stream().reduce((x, y) -> x + y); // list1中元素求和
System.out.println(reduce.get());
Integer sum = list1.stream().reduce(0, Integer::sum); // list1中元素求和
System.out.println(sum);
Integer sum2 = list1.stream().reduce(10, Integer::sum); // 10 + list1中元素求和
System.out.println(sum2);
- allMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false
- noneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false
- anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
- findFirst:返回流中第一个元素
- findAny:返回流中的任意元素
- count:返回流中元素的总个数
- max:返回流中元素最大值
- min:返回流中元素最小值
本文介绍 Java 8 中的 Stream API,演示如何利用 Stream 进行复杂的数据处理操作,包括过滤、映射、排序等,并展示了 Stream 的创建方式及常用方法如 filter、map 和 reduce 的使用。

410

被折叠的 条评论
为什么被折叠?



