在findFirst()中使用pipeline.findFirst ()和map()是否有效,而map是中间操作。
this.list.stream().filter(t -> t.name.equals("pavan")).findFirst().map(toUpperCase()).orElse(null);在流水线上使用map是否有效??
发布于 2016-08-05 08:19:12
是的,可以在findFirst之后使用map。这里需要知道的关键是,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!");
}代码片段的另一个错误是您使用toUpperCase的位置。它需要一个字符串,而在代码段中传递的隐式参数是Person类的对象。
https://stackoverflow.com/questions/38518313
复制相似问题