首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Map与FindFirst

Map与FindFirst
EN

Stack Overflow用户
提问于 2016-07-22 04:43:38
回答 1查看 24.7K关注 0票数 4

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

代码语言:javascript
复制
this.list.stream().filter(t -> t.name.equals("pavan")).findFirst().map(toUpperCase()).orElse(null);

在流水线上使用map是否有效??

EN

回答 1

Stack Overflow用户

发布于 2016-08-05 08:19:12

是的,可以在findFirst之后使用map。这里需要知道的关键是,findFirst()返回一个Optional,因此,如果不首先检查可选选项是否有值,就不能简单地使用返回值。下面的片段假设您正在处理Person类的对象列表。

代码语言:javascript
复制
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类的对象。

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38518313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档