概念
- 顺序遍历每一个进行操作 和 对集合的聚合操作 可以类比数据库的聚合函数 sequential and parallel aggregate operations
顶层接口
BaseStream
- 终端操作
Iterator<T> iterator()
返回集合的迭代器Spliterator<T> spliterator()
返回集合的分割器 没搞懂怎么用,干啥用的?
中间状态操作
S sequential()
返回一个顺序流int[] array = {1,2,4,6,3,1,3}; Stream<int[]> sequential = Stream.of(array).sequential();
S parallel()
返回一个并行流??S unordered()
返回一个无序流 ??
其他操作
boolean isParallel()
判断当前流是否可执行终端操作S onClose(Runnable closeHandler)
当流被关闭时触发的动作。
- 终端操作
Collector
Supplier<A> supplier()
返回一个可变的容器??BiConsumer<A,T> accumulator()
把多个值折叠入一个可变容器???BinaryOperator<A> combiner()
组合两个结果Function<A,R> finisher()
把一个中间结果变成一个最终结果Set<Collector.Characteristics> characteristics()
特性集合???static <T,R> Collector<T,R,R> of(Supplier<R> supplier,
Collector的构造器
BiConsumer<R,T> accumulator,
BinaryOperator<R> combiner,
Collector.Characteristics... characteristics)
Collector<Widget, ?, TreeSet<Widget>> intoSet = Collector.of(TreeSet::new, TreeSet::add, (left, right) -> { left.addAll(right); return left; });
Collector<Employee, ?, Integer> summingSalaries = Collectors.summingInt(Employee::getSalary))
Collector<Employee, ?, Map<Department, Integer>> summingSalariesByDept = Collectors.groupingBy(Employee::getDepartment, summingSalaries);
DoubleStream
double相关的所有的你能想到的操作DoubleStream peek(DoubleConsumer action)
DoubleStream.of(1, 2, 3, 4) .filter(e -> e > 2) .peek(e -> System.out.println("Filtered value: " + e)) .map(e -> e * e) .peek(e -> System.out.println("Mapped value: " + e)) .sum();
double sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToDouble(w -> w.getWeight()) .sum();
Collectors
// Accumulate names into a List List<String> list = people.stream().map(Person::getName).collect(Collectors.toList()); // Accumulate names into a TreeSet Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new)); // Convert elements to strings and concatenate them, separated by commas String joined = things.stream() .map(Object::toString) .collect(Collectors.joining(", ")); // Compute sum of salaries of employee int total = employees.stream() .collect(Collectors.summingInt(Employee::getSalary))); // Group employees by department Map<Department, List<Employee>> byDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); // Compute sum of salaries by department Map<Department, Integer> totalByDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.summingInt(Employee::getSalary))); // Partition students into passing and failing Map<Boolean, List<Student>> passingFailing = students.stream() .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
用例
- sum 求和
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();