我有一部分非常有趣的代码,我想重构为使用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流重构它?

最佳答案

可以使用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循环。

07-27 21:20