在 Java 8 中递归展平整嵌套映射的值

2022-09-02 21:05:46

给定 一个 ,其中的值要么是 a 要么是另一个,那么使用 Java 8 如何将映射平展到单个值列表?Map<String, Object>StringMap<String, Object>

例:

Map - "key1" -> "value1"
    - "key2" -> "value2"
    - "key3" -> Map - "key3.1" -> "value3.1"
                    - "key3.2" -> "value3.2"
                    - "key3.3" -> Map - "key3.3.1" -> "value3.3.1"
                                      - "key3.3.2" -> "value3.3.2" 

对于上面的例子,我想要以下列表:

value1
value2
value3.1
value3.2
value3.3.1
value3.3.2

我知道它可以像这样完成:

public static void main(String args[]) throws Exception {
    //Map with nested maps with nested maps with nested maps with nested......
    Map<String, Object> map = getSomeMapWithNestedMaps();

    List<Object> values = new ArrayList<>();
    addToList(map, values);

    for (Object o:values) {
        System.out.println(o);
    }
}

static void addToList(Map<String, Object>map, List<Object> list) {
    for (Object o:map.values()) {
        if (o instanceof Map) {
            addToList((Map<String, Object>)o, list);
        } else {
            list.add(o);
        }
    }
}

我怎样才能做到这一点?Stream

编辑:

经过一番思考,我想通了:

public static void main(String args[]) throws Exception {
    //Map with nested maps with nested maps with nested maps with nested......
    Map<String, Object> map = getSomeMapWithNestedMaps();
    //Recursively flatten maps and print out all values
    List<Object> list= flatten(map.values().stream()).collect(Collectors.toList());
}

static Stream<Object> flatten(Stream<Object> stream) {
    return stream.flatMap((o) ->
        (o instanceof Map) ? flatten(((Map<String, Object>)o).values().stream()) : Stream.of(o)
    );
}

答案 1

您可以定义一个递归方法,该方法将一个映射展平,并将其用作函数,或者通过直接调用它来使用它。Stream#flatMap

例:

public class FlatMap {

    public static Stream<Object> flatten(Object o) {
        if (o instanceof Map<?, ?>) {
            return ((Map<?, ?>) o).values().stream().flatMap(FlatMap::flatten);
        }
        return Stream.of(o);
    }

    public static void main(String[] args) {
        Map<String, Object> map0 = new TreeMap<>();
        map0.put("key1", "value1");
        map0.put("key2", "value2");
        Map<String, Object> map1 = new TreeMap<>();
        map0.put("key3", map1);
        map1.put("key3.1", "value3.1");
        map1.put("key3.2", "value3.2");
        Map<String, Object> map2 = new TreeMap<>();
        map1.put("key3.3", map2);
        map2.put("key3.3.1", "value3.3.1");
        map2.put("key3.3.2", "value3.3.2");

        List<Object> collect = map0.values().stream()
                                            .flatMap(FlatMap::flatten)
                                            .collect(Collectors.toList());
        // or
        List<Object> collect2 = flatten(map0).collect(Collectors.toList());
        System.out.println(collect); 
    }
}

对于给定的嵌套地图,它将打印

[值1、值2、值3.1、值3.2、值3.3.1、值3.3.2]


答案 2