【问题标题】:Java 8 : Filter 2 different JSON arrays according to certain fieldsJava 8:根据某些字段过滤 2 个不同的 JSON 数组
【发布时间】:2018-10-15 22:08:18
【问题描述】:

这可能很傻,但我想不通,我有 2 个不同的模式 JSON 数组。

JSON 数组 A

[
  {
     "name": "Robin",
     "uid": 1234   
  },  
  {
     "name": "Tom",
     "uid": 8768   
  },   
  {
     "name": "Eddy",
     "uid": 4534   
  }
]

JSON 数组 B

[
  {
     "group": "Reign",
     "admin": 8768   
  },  
  {
     "group": "Hounds",
     "admin": 1234   
  },   
  {
     "group": "Dukes",
     "admin": 5996   
  }
]

JSON 数组 A 中的 uid 和 JSON 数组 B 中的 admin 字段的值本质上是相同的。列表非常大,因此迭代非常昂贵。

我的任务是根据这 2 个字段(uid 和管理员)获取数组 A 的元素与数组 B 的元素匹配。还需要收集Array A的多余元素和Array B的多余元素。

到目前为止我做了什么

List<JsonObject> listOutput = jsonDataAList.stream()
                .filter(e -> jsonDataBList.stream()
                        .map(JsonDataA::getUid)
                        .anyMatch(admin -> admin.equals(e.getAdmin())))
                .collect(Collectors.toList());

失望的选民请抽出时间解释

提前致谢。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • @JacobG。 jsonDataAList.stream().filter(e -> jsonDataBList.stream().map(JsonDataA::getUid).anyMatch(admin -> admin.equals(e.getUid()))).collect(Collectors.toList() );
  • 初次使用时需要它还是每次都要解析它?
  • @DhruvSehgal 我将准备好将两个数组解析为 List

标签: java json filter java-stream


【解决方案1】:

假设 uid 是唯一的,我会将两个 Json 都转换为 Map&lt;Integer, String&gt;,然后使用下一个 answer

你可以使用GuavaMaps.difference(Map<K, V> left, Map<K, V> right) 方法。它返回一个 MapDifference 对象,它具有获取所有四种地图条目的方法:

  • 在左右地图中同样存在
  • 仅在左侧地图中
  • 仅在右侧地图中
  • 两个地图中都有键,但值不同

【讨论】:

    【解决方案2】:

    自己解决

    private List<JsonObject> getExcessElements(List<JsonObject> primaryList, List<JsonObject> secondaryList, String primaryKey, String secondaryKey) {
    List<JsonObject> excessInPrimary = primaryList.stream()
    .filter(e -> (secondaryList.stream()
    .filter(d -> d.get(secondaryKey).equals(e.get(primaryKey)))
    .count()) < 1)
    .collect(Collectors.toList());
    return excessInPrimary;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      相关资源
      最近更新 更多