Map和FindFirst

ppp*_*van 4 java java-stream

在pipeline.findFirst中使用findFirst()和map()是有效的,而map是中间操作.

this.list.stream().filter(t -> t.name.equals("pavan")).findFirst().map(toUpperCase()).orElse(null);
Run Code Online (Sandbox Code Playgroud)

在上面的管道中使用map是否有效?

Ran*_*jan 7

是的,你可以使用map之后findFirst.这里要知道的关键是findFirst()返回一个Optional,因此,你不能简单地使用返回值,而不首先检查可选项是否有值.下面的代码段假定您正在使用Person类的对象列表.

Optional<String> result = this.list.stream()
    .filter(t -> t.name.equals("pavan")) // Returns a stream consisting of the elements of this stream that match the given predicate.
    .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.
    .map(p -> p.name.toUpperCase()); // If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

// This check is required!
if (result.isPresent()) {
    String name = result.get(); // If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
    System.out.println(name);
} else {
    System.out.println("pavan not found!");
}
Run Code Online (Sandbox Code Playgroud)

你的代码片段还有一个错误就是你正在使用的地方toUpperCase.它需要一个String,而在你的代码片段中传递的隐式参数是Person类的对象.