zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Java Stream] Basic terminal operations

JAVA stream Basic terminal operations
2023-09-14 09:00:46 时间

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