stream - 如何从 MAP 获取 MATCH 值
问题描述
我试图弄清楚如何获取匹配值并将其存储在字符串变量中,这就是我所做的:
出于示例目的,我创建了以下内容:
Map<Attachment, String> mapattach = new HashMap<Attachment, String>();
Attachment a1 = new Attachment();
a1.setId("one1");
a1.setName("one");
a1.setUrl("http://1.com");
Attachment a2 = new Attachment();
a2.setId("two2");
a2.setName("two");
a2.setUrl("http://2.com");
Attachment a3 = new Attachment();
a3.setId("three3");
a3.setName("three");
a3.setUrl("http://3.com");
mapattach.put(a1, "one1");
mapattach.put(a2, "two22");
mapattach.put(a3, "three33");
//java stream
//it will match only one item and it returns
String matchFound = mapattach.entrySet().stream()
.filter( f -> recordIds.contains(f.getKey().getId()))
.findFirst().toString();
上面的代码返回一条记录的字符串:
结果:
Optional[class Attachment {
name: one
id: one1
mimeType: null
url: http://1.com
referenceId: null }=one1]
但我想要的是url
我该怎么做?
解决方案
你快到了,这应该可以解决问题:
Optional<String> optionalUrl = mapattach.entrySet().stream()
.filter(f -> recordIds.contains(f.getKey().getId()))
.findFirst()
.map(attachmentStringEntry -> attachmentStringEntry.getKey().getUrl());
urlMatchFound = optionalUrl.get(); // remember that it might not be present.
推荐阅读
- amazon-web-services - 每 11 秒运行一次代码
- python-3.x - Azure Put Blob API 返回规范化标头中的文件大小不匹配
- java - 在运行时检查 --module-path 值
- html - Nav、Subnav 和 Sidenav 已修复,而正文滚动
- odoo-10 - 如何正确继承odoo中的继承视图?
- c# - 尝试使用 c# asp.net 后面的代码将超链接分配到 PDF 内的 pdf 位置
- java - 从 java 应用程序备份 MySQL 数据库
- javascript - 反应未定义的地图输出
- php - 使用参数流明重定向
- microsoft-graph-api - Microsoft Graph - 找不到邮箱