Java 8流和lambda

时间:2015-06-23 15:12:21

标签: java lambda java-8 java-stream

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

1 个答案:

答案 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循环。