admin管理员组

文章数量:1401969

I have quite simple task: there is a List<Map> exposed from unsorted YAMLs and JSONs. I need to filter the list to find some particular data structures and extract some part of them -- four different filter conditions and extracting of correspondent parts.

My idea was to use streams but they don't support forking or multi-filtering with following split mapping and then joining. I solved the task by mapping the following function to the list, but I don't like its imperative style in functional context:

private Stream<String> getModelNames(Map<String, Map<String, Object>> expression) {
    if (expression.containsKey("keyA")) {
        return Stream.of((String) expression.get("keyA").get("model_name"));
    } else if (expression.containsKey("keyB")) {
        return Stream.of((String) expression.get("keyB").get("model_name"));
    } else if (expression.containsKey("keyC")) {
        return Stream.of((String) expression.get("keyC").get("model_name"));
    } else if (expression.containsKey("keyD")) {
        return ((List)expression.get("keyD").get("cases")).stream()
                .map(cases -> ((List)cases).get(1));
    } else {
        return Stream.of();
    }
}

List<String> modelNames = ruleRepository
       .getSomeData()
       .stream()
       .map(expression -> (Map)yaml.load(expression))
       .map(expression -> getModelNames(expression))
       .flatMap(s -> s)
       .toList();

The question is there more elegant/functional solution?

本文标签: Is there elegant way to fork and join Java streamsStack Overflow