[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))

 

上一篇:MySQL高级——索引失效案例2


下一篇:转:Java NIO系列教程(一)Java NIO 概述