我有非常有趣的代码部分,我想重构使用java 8流API功能
Map<String, Object> user = ...// pull user from somewhere
List<Map<String, Object>> attributes = ...// pull attributes from somewhere
List<Map<String, Object>> processedAttributes = new ArrayList<>();
for (Map<String, Object> attribute : attributes) {
if (!((List<Map<String, Object>>) attribute.get("subAttributes")).isEmpty()) {
for (Map<String, Object> subAttribute : (List<Map<String, Object>>) attribute.get("subAttributes")) {
if (!user.containsKey(subAttribute.get("name"))
&& Boolean.TRUE.equals(subAttribute.get("required"))) {
processedAttributes.add(subAttribute);
}
}
}
}
如何使用java 8流重构?
答案 0 :(得分:3)
可以使用flatMap
:
List<Map<String, Object>> processedAttributes = attributes.stream()
.flatMap(
attribute -> ((List<Map<String, Object>>) attribute
.get("subAttributes")).stream())
.filter(subAttr -> !user.containsKey(subAttr.get("name"))
&& Boolean.TRUE.equals(subAttr.get("required")))
.collect(Collectors.toList());
请注意,代码中不需要isEmpty
检查:如果List
为空,则无论如何都不会执行for
循环。