Java 8:如何在不将流转换回列表并在第 0 个位置获取值的情况下获取列表内对象中的特定值?
Java 8: How to get particular value within object inside list without converting stream back to list and fetch value at 0th location?
我需要 return 来自 href()
的链接列表中的值,其中 Rel 值为 String
。
class Links{
String rel;
String href;
}
class 2{
List<Links> links
}
下面的代码是这样做的,但看起来并不酷
return links.stream().filter(d -> StringUtils.equalsIgnoreCase(d.getRel(), "Self")).collect(Collectors.toList()).get(0).getHref();
有没有办法直接从列表中获取 getHref
来代替 converting it back to list
和 get 0th element
。
是的,使用 findFirst()
:
return links.stream()
.filter(d -> StringUtils.equalsIgnoreCase(d.getRel(), "Self"))
.findFirst() // returns an Optional<Links>
.map(Links::getHref) // returns an Optional<String>
.orElse(null); // returns String (either getHref of the found Links instance, or
// null if no instance passed the filter)
我需要 return 来自 href()
的链接列表中的值,其中 Rel 值为 String
。
class Links{
String rel;
String href;
}
class 2{
List<Links> links
}
下面的代码是这样做的,但看起来并不酷
return links.stream().filter(d -> StringUtils.equalsIgnoreCase(d.getRel(), "Self")).collect(Collectors.toList()).get(0).getHref();
有没有办法直接从列表中获取 getHref
来代替 converting it back to list
和 get 0th element
。
是的,使用 findFirst()
:
return links.stream()
.filter(d -> StringUtils.equalsIgnoreCase(d.getRel(), "Self"))
.findFirst() // returns an Optional<Links>
.map(Links::getHref) // returns an Optional<String>
.orElse(null); // returns String (either getHref of the found Links instance, or
// null if no instance passed the filter)