[英]How to return Optional String using Java 8 streams
This code should return the Optional
String when given siteUrl
contains key from the predefined list of pairs (or Optional.empty()
otherwise). 当给定的
siteUrl
包含预定义的配对对中的键时,此代码应返回Optional
String(否则为Optional.empty()
)。
Is there a better way than using new Pair(null, null)
here? 有没有比这里使用
new Pair(null, null)
更好的方法? Or maybe change the whole expression? 或者也许改变整个表情?
static Optional<String> get(String siteUrl) {
return Optional.ofNullable(URL_TO_ENVIRONMENT
.stream()
.filter(p -> siteUrl.contains(p.getKey()))
.findFirst().orElse(new Pair(null, null)).getValue());
}
private static final List<Pair> URL_TO_ENVIRONMENT = buildList();
private static List<Pair> buildList() {
return Arrays.asList(
new Pair("aaa.mysite.com", "aaa_something"),
new Pair("bbb.mysite.com", "bbb_something"),
new Pair("ccc.mysite.com", "ccc_comething"));
}
return URL_TO_ENVIRONMENT.stream()
.filter(p->siteUrl.contains(p.getKey()))
.map(Pair::getvalue)
.findFirst();
Do you specifically need the first match? 您是否特别需要第一场比赛? if you just want any match, use
findAny
instead of findFirst
. 如果您只想要任何匹配项,请使用
findAny
而不是findFirst
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.