【问题标题】:Java - Looping over complex collection of ObjectsJava - 循环复杂的对象集合
【发布时间】:2021-07-14 21:49:00
【问题描述】:

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

  • 我有一个Collection<Object>,其中包含一个Array<E>LinkedHashMap<K,V>,我正试图从中提取值。
  • 我尝试了各种循环来获取 Key、Value 对,但没有运气,例如;

物体的样子;

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..
              }
            }
        }

我想知道有效执行此操作的最佳方法是什么,有什么建议吗?谢谢。

【问题讨论】:

    标签: java loops arraylist collections linkedhashmap


    【解决方案1】:

    Arrays.asList(something) 将生成包含一个元素的列表。你不需要这样做。

    Object object = param.get("idsToExclude");
    

    您可以检查对象并投射到列表。

    if (object instanceof List) {
      List list = (List) object;
    }
    

    列表中的每一项都需要检查和转换。

    for (Object item : list) {
      if (item instanceof Map) {
        Map map = (Map) item;
      }
    }
    

    您可以从地图项中获取键和值。

    Object key = map.getKey();
    Object value = map.getValue();
    

    完整示例:

    Object object = param.get("idsToExclude");
    if (object instanceof List) {
      List list = (List) object;
      for (Object item : list) {
        if (item instanceof Map) {
          Map map = (Map) item;
          Object key = map.getKey();
          Object value = map.getValue();
          // You can cast key and value to other object if you need it
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      只要输入集合的内容可以指定为Collection&lt;List&lt;Map&lt;K, V&gt;&gt;&gt;(注意使用接口ListMap而不是实现ArrayListLinkedHashMap),实现会更合适使用K, V 键入的通用方法,以摆脱instanceof 和显式转换:

      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()
               ));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        • 1970-01-01
        • 2016-02-20
        • 2020-03-02
        • 1970-01-01
        • 1970-01-01
        • 2014-05-09
        相关资源
        最近更新 更多