[英]Logging warning message while processing streams in java
I want to log error messages if the map rdsDesksByName.get(e.getKey())
does not have any value for the key.如果映射rdsDesksByName.get(e.getKey())
没有任何键值,我想记录错误消息。 How can I handle this within streams?我如何在流中处理这个问题?
Currently I return createDeskWithScope(rdsDesksByName.get(e.getKey()),ds.outOfScope())
, but how can I enhance this function to log an error message if rdsDesksByName
does not have any value for the key, otherwise it should process as usual目前我返回createDeskWithScope(rdsDesksByName.get(e.getKey()),ds.outOfScope())
,但是如果rdsDesksByName
没有任何键值,我如何增强此功能以记录错误消息,否则它应该处理照常
List<Desk> desks = deskScopesByName.entrySet()
.stream()
.flatMap(e -> {
return deskScopesByName.get(e.getKey())
.stream()
.map(ds -> {
return createDeskWithScope(rdsDesksByName.get(e.getKey()), ds.outOfScope());
});
})
.collect(Collectors.toList());
In the flatmapping operation, find an object by the key and use the if-else
condition:在flatmapping操作中,通过key找到一个对象,并使用if-else
条件:
null
(no value for such key), log a message and return Stream.empty()
.如果该对象为null
(此类键没有值),则记录一条消息并返回Stream.empty()
。createDeskWithScope
method.否则,使用createDeskWithScope
方法继续处理。Here is how the code might look like (untested, but should give you an idea):下面是代码的样子(未经测试,但应该给你一个想法):
List<Desk> desks = deskScopesByName.entrySet()
.stream()
.flatMap(entry -> {
String key = entry.getKey();
Desk rdsDesk = rdsDesksByName.get(key);
if (rdsDesk == null) {
log.warn("There is no Desk present for {}", key);
return Stream.empty();
} else {
return entry.getValue()
.stream()
.map(ds -> createDeskWithScope(rdsDesk, ds.outOfScope()));
}
})
.collect(Collectors.toList());
I recommend wrapping the flatmapping operation inside a method.我建议将平面映射操作包装在一个方法中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.