[英]Java Return an Optional<String> from findFirst()
I am working with Optional now, and I have to return a String from a findFirst() method. 我现在正在使用Optional,我必须从findFirst()方法返回一个String。 I know that findFirst returns an Optional but I would like to return an
Optional<String>
as in in the method signature. 我知道findFirst返回一个Optional,但是我想在方法签名中返回一个
Optional<String>
。
@Override
public Optional<String> findBetweenMinAgeAndMaxAge(int kidAge, String id) {
String query = buildFindRoomByKidAge();
JsonObject params = JsonObject.create()
.put(JAVA_TYPE_PARAM, ShipRoom.class.getName())
.put(ID_PARAM, id)
.put(KID_AGE_PARAM, kidAge);
N1qlQuery queryWithParameter = N1qlQuery.parameterized(query, params);
return template.findByN1QLProjection(queryWithParameter, Room.class)
.stream()
.findFirst();
}
Is there any sophisticated way to achieve this? 有没有复杂的方法来实现这一目标?
I made the next: 我做了下一个:
@Override
public Optional<String> findBetweenMinAgeAndMaxAge(int kidAge, String id) {
String query = buildFindRoomByKidAge();
JsonObject params = JsonObject.create()
.put(JAVA_TYPE_PARAM, ShipRoom.class.getName())
.put(ID_PARAM, id)
.put(KID_AGE_PARAM, kidAge);
N1qlQuery queryWithParameter = N1qlQuery.parameterized(query, params);
return Optional.ofNullable(template.findByN1QLProjection(queryWithParameter, Room.class)
.stream()
.findFirst().get().getId());
}
But I think there should be a better solution. 但我认为应该有更好的解决方案。 Any advice?
有什么建议?
Thanks! 谢谢!
Use Optional.map()
: 使用
Optional.map()
:
return template.findByN1QLProjection(queryWithParameter, Room.class)
.stream()
.findFirst()
.map(Room::getId)
map()
accepts a function which the result is returned if a value is present in the optional. map()
接受一个函数,如果可选项中存在值,则返回结果。
Since you already have an Optional<Room>
as a result you can map it further use Optional#map
as: 由于您已经有一个
Optional<Room>
,因此您可以进一步使用Optional#map
作为:
return template.findByN1QLProjection(queryWithParameter, Room.class)
.stream()
.findFirst()
.map(room -> room.getId());
Do note, as per your second revision, the map
takes care of the id
being null
on its own and returns Optional.empty
for such values. 请注意,根据您的第二个修订版,
map
会自行处理id
为null
,并为这些值返回Optional.empty
。 From the javadoc: 来自javadoc:
If the mapping function returns a null result then this method returns an empty Optional.
如果映射函数返回null结果,则此方法返回空Optional。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.