美文网首页
Java Stream

Java Stream

作者: bowen_wu | 来源:发表于2021-07-21 16:35 被阅读0次

概述

  • 一个流
  • 不易出错
  • 简化代码
  • 可读性 & 可维护性 提升
  • 不会影响之前的数据

创建流

  • Collection.stream()
  • Stream.of()
  • String.chars => public final class String implements java.io.Serializable, Comparable<String>, CharSequence => CharSequence.chars(): IntStream => 生成 int 的流
  • IntStream.range() => Returns a sequential ordered IntStream from startInclusive to endExclusive by an incremental step of 1 => 生成 int 的流

Stream API

Intermediate Operation

@return the new stream

  • public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) => Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

  • public static<T> Stream<T> empty() => Returns an empty sequential stream

  • Stream<T> filter(Predicate<? super T> predicate) => Returns a stream consisting of the elements of this stream that match the given predicate

  • <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper); => Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element => 每使用一次 flat 降低一个维度

  • DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);

  • IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);

  • LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);

  • Stream<T> limit(long maxSize); => Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length

  • <R> Stream<R> map(Function<? super T, ? extends R> mapper); => Returns a stream consisting of the results of applying the given function to the elements of this stream

  • DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);

  • IntStream mapToInt(ToIntFunction<? super T> mapper);

  • LongStream mapToLong(ToLongFunction<? super T> mapper);

  • Stream<T> peek(Consumer<? super T> action); => Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline

  • Stream<T> skip(long n); => Returns a stream consisting of the remaining elements of this stream after discarding the first n elements fo the stream. If this stream contains fewer than n elements then an empty stream will be returned

  • Stream<T> sorted(); => Returns a stream consisting of the elements of this stream, sorted according to natural order

  • Stream<T> sorted(Comparator<? super T> comparator); => Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator

  • Stream<T> distinct() => ???

Terminal Operation

返回非 Stream 的操作,包括 void,一个流只能被消费一次

  • <R, A> R collect(Collector<? super T, A, R> collector); => 最强大的操作 => Performs a mutable reduction operation on the elements of this stream using a Collector.
  • boolean allMatch(Predicate<? super T> predicate); => Returns whether all elements of this stream match the provided predicate
  • boolean anyMatch(Predicate<? super T> predicate); => Returns whether any elements of this stream match the provided predicate
  • boolean noneMatch(Predicate<? super T> predicate); => Returns whether no elements of this stream match the provided predicate
  • long count() => Returns the count of elements in this stream
  • Optional<T> findAny() => Returns an Optional Describing some element of the stream, or an empty Optional if the stream is empty => 需要用在 filter 后面
  • Optional<T> findFirst() => Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned => 需要用在 filter 后面
  • void forEach(Consumer<? super T> action); => Performs an action for each element of this stream
  • void forEachOrdered(Consumer<? super T> action); => Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order
  • Optional<T> max(Comparator<? super T> comparator); => Returns the maximum element of this stream according to the provided Comparator
  • Optional<T> min(Comparator<? super T> comparator); => Returns the minimum element of this stream according to the provided Comparator
  • Optional<T> reduce(BinaryOperator<T> accumulator); => Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value
  • T reduce(T identity, BinaryOperator<T> accumulator)
  • <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);

java.util.Collectors API

// 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));

// TODO: Collectors API

并发流 java.util.Collection.parallelStream

java.util.stream.parallel() => 将一个流转化为并发方法 => 注意:使用要小心,性能要测试

  • 可以通过并发提高互相独立的操作的性能
  • 在正确的使用前提下,可以获得近似线性的性能提升
long t0 = System.currentTimeMillis();
IntStream.range(1, 100_0000).filter(Primes::isPrime).count();
System.out.println(System.currentTimeMillis() - t0);

long t1 = System.currentTimeMillis();
IntStream.range(1, 100_0000).parallel().filter(Primes::isPrime).count();
System.out.println(System.currentTimeMillis() - t1);

知识点

  1. List 有序列表。Set 无序集合,不能包含重复的元素
  2. private 的访问限定是在当前的编译单元 => compilation unit (文件)
  3. Optional 需要和函数式一起用,不要将 Optional 当成空指针使用,Optional 一般只当做返回值,如果作为参数,会有警告,不应该将 Optional 传来传去
    Optional<User> optionalUser = users.stream().filter(User::isSurnameZhang).findAny();
    
    // 当做空指针使用 => 使用不当
    if(optionalUser.isPresent()) {
        System.out.println(optionalUser.get().getName);
    } else {
        throw new IllegalStateException();
    }
    
    // 函数式 => 可以级联,上述可以变为
    optionalUser.orElseThrow(IllegalStateException::new);
    optionalUser.ifPresent(System.out::println);
    
    User user = users.stream().filter(User::isSurnameZhang).findAny().orElseThrow(IllegalStateException::new);
    System.out.println(user.getName());
    
  4. Effective Java Item 42 - 48

相关文章

网友评论

      本文标题:Java Stream

      本文链接:https://www.haomeiwen.com/subject/cburmltx.html