[Java Stream] Basic terminal operations

To void: 

  forEach, forEachOrdered, peek

stream.peek(System.out::println) // print without termination
    .filter(n -> n > 0)
    .distinct()
    .limit(10)
    .forEach(System.out::println);

To boolean:

  allMatch, anyMatch, noneMatch

Collection<Employee> emps = ...;

boolean allValid = emps.stream()
    .allMatch(e -> e.getName != null && e.getName().length() > 0);

To array:

  toArray

Stream<Employee> emps = ...;

Object[] lowEmps = emps.filter(e -> e.getSalary() < 2000)
                                      .toArray();
Employee[] lowEMps = emps.filter(e -> e.getSalary() < 2000)
                                          .toArray(Employee[]::new);

To long:

  count

To T:

  findFirst, findAny, min, max

String result = stream.min(comparator).orElse("default string");
Collection<String> strings = ...;

Optional<String> longest = 
    strings.stream()
               .max(Comparator.comparingInt(String::length))
原文地址:https://www.cnblogs.com/Answer1215/p/14306018.html