如何获取哈希图中特定键的值列表?

问题描述 投票:0回答:1

我有一个json1数据如下-

    "data": {
          "user": [
            {
              "id": "5735",
              "items": [
                {
                  "itemId": "698726h",
                  "state": "new"
                },
                {
                  "itemId": "999",
                  "state": "new"
                }
              ]
            }
          ]

与另一个 json2 模型进行比较,如下 -

    "entity": {
          "user": [
            {
              "id": "5735",
              "items": [
                {
                  "itemId": "698726h",
                  "state": "old"
                }
              ]
            }
          ]

在上面的jsons中,user是一个对象数组,Items也是一个对象数组。我想比较

user.id()
,如果它匹配,则我迭代项目对象,当 ItemId 也匹配时,相应的状态属性将从“新”更改为“旧”。在上面的示例中,“ItemId”的“状态”:“698726h”已从新更改为旧。

为了实现上述要求,我创建了一个哈希映射,其键为

user.id()
,相应的 ItemId 将存储为字符串数组,作为特定键的值。创建 hashmap 后,我将其与其他 json 进行比较。我搜索与另一个 json 的 user.id() 匹配的键,当它匹配时,我会获取该键的所有相应值或 ItemId 列表。现在,我在另一个 json 中将 ItemIds 的状态从“新”更改为“旧”,以获取 ItemsIds 的采购列表。为了实现同样的目标,我做了以下工作 -

HashMap<String,List<String>> map = new HashMap<>();

    json1.data().user().forEach(
      user -> {
        map.put(user.id(),user.items().stream()
          .map(k->k.itemId()).collect(Collectors.toList()));
      }
    );

//Then I iterate through the json2 and compare the key of the hashmap to the user.id() in the json2-

json2.entity().user().forEach(
user ->{
If(map.containsKey(user.id())){
   
 List<String> val = map.get(user.id()); // ERROR //NOT WORKING

//Here I want to fetch all the corresponding itemIds as a list of string as provided in the map.
//After getting the list of itemids, I want to change the state of the corresponding itemIds from "new" to "old".
  }
 }
);

错误是-

不兼容的类型。找到“java.lang.Object”,必需:“java.util.List

如果事情变得复杂,有其他解决方案吗?

java arrays list object hashmap
1个回答
0
投票

您可以尝试以下方法:

 List<String> val = (List<String>) map.get(user.id());
© www.soinside.com 2019 - 2024. All rights reserved.