首页 > 解决方案 > Java - 循环复杂的对象集合

问题描述

我有一个关于循环包含复杂对象的集合的一般问题。

对象看起来像;

复杂对象

Collection<Object> dsidsToExclude = Arrays.asList(param.get("idsToExclude"));
    for(Object id : dsidsToExclude) {
            if(id instanceof ArrayList) {
            // Loop over the list of <K,V>
            for(Object kv : id) {
               // I want to get extract the kv pairs here..
              }
            }
        }

我想知道有效地做到这一点的最佳方法是什么,有什么建议吗?谢谢。

标签: javaloopsarraylistcollectionslinkedhashmap

解决方案


只要输入集合的内容可以指定为Collection<List<Map<K, V>>>(注意使用接口ListMap而不是实现ArrayList和),实现类型为的泛型方法以摆脱和显式转换LinkedHashMap会更合适:K, Vinstanceof

public static <K, V> doSomething(Collection<List<Map<K, V>>> input) {
    for (List<Map<K, V>> list : input) {
        for (Map<K, V> map : list) {
            for (Map.Entry<K, V> entry : map.entrySet()) {
                // do what is needed with entry.getKey() , entry.getValue()
            }
        }
    }
}

类似地,方法forEach可以用于集合、列表和映射:

public static <K, V> doSomethingForEach(Collection<List<Map<K, V>>> input) {
    input.forEach(list ->
        list.forEach(map ->
            map.forEach((k, v) -> // do what is needed with key k and value v
                System.out.printf("key: %s -> value: %s%n", k, v);
            );
        )
    );
}

此外,还可以使用 Stream API,尤其flatMap是访问所有最内层地图的内容。可选地,null可以过滤值,如下所示

public static <K, V> doSomethingStream(Collection<List<Map<K, V>>> input) {
    input.stream()                 // Stream<List<Map<K, V>>>
         .filter(Objects::nonNull) // discard null entries in collection
         .flatMap(List::stream)    // Stream<Map<K, V>>
         .filter(Objects::nonNull) // discard null entries in list
         .flatMap(map -> map.entrySet().stream()) // Stream<Map.Entry<K, V>>
         .forEach(e -> System.out.printf(
             "key: %s -> value: %s%n", e.getKey(), e.getValue()
         ));
}

推荐阅读