簡體   English   中英

如何將java對象列表轉換為Map <String, Map<String, String> &gt;

[英]How to convert a list of java objects to Map<String, Map<String, String>>

我有一個 Java 對象列表,如下所示:

[
  {
    id: "frwfhfijvfhviufhbviufg",
    country_code: "DE",
    message_key: "key1",
    translation: "This is the deutsch translation"
  },
  {
    id: "dfregregtegetgetgttegt",
    country_code: "GB",
    message_key: "key1",
    translation: "This is the uk translation"
  },
  {
    id: "frffgfbgbgbgbgbgbgbgbg",
    country_code: "DE",
    message_key: "key2",
    translation: "This is the again deutch translation"
  }
]

如何將其轉換為Map<String, Map<String, String>>如下所示:

{
  "DE": {
    "key1": "This is the deutsch translation",
    "key2": "This is the again deutch translation"
  },
  "GB": {
    "key1": "This is the uk translation"
  }
}

我是 Java 新手,下面是我的代碼,但代碼不正確:

Map<String, Translations> distinctTranslations = customTranslationsEntities
        .stream().collect(Collectors.groupingBy(
                CustomTranslationsEntity::getCountryCode,
                Collectors.toMap(
                        CustomTranslationsEntity::getMessageKey,
                        CustomTranslationsEntity::getTranslation),

                )))

其中 Translations 是 proto 緩沖區消息,如下所示:

message Translations {
  map<string, string> translations = 1;
}

這里map<string, string> translations意味着像"key1", "This is the deutsch translation" ......像這樣的地圖。

輸出應該是Map<String, Map<String,String>>

Map<String, Map<String,String>>
    distinctTranslations = customTranslationsEntities
            .stream()
            .collect(Collectors.groupingBy(CustomTranslationsEntity::getCountryCode,
                                    Collectors.toMap(
                                            CustomTranslationsEntity::getMessageKey,
                                            CustomTranslationsEntity::getTranslation,
                                            (v1,v2)->v1)));

我添加了一個合並功能,以防有重復的鍵。

如果你想在不使用流的情況下做到這一點,那么

private List<MyObject> list = // Your object List
private Map<String, Map<String, String>> map = new HashMap<>();

for(MyObject object : list){
    Map<String, String> localMap;
    localMap = map.getOrDefault(object.country_code, new HashMap<>());
    localMap.put(object.message_key, object.translation);
    if(!map.containsKey(object.country_code)){
        map.put(object.country_code, localMap);
    }
}

您的代碼正確且有效。 只需添加一個合並函數即可避免為重復鍵獲取IllegalStateException

以這種方式更新Collector.toMap()

Collectors.toMap(..., (trans1, trans2) -> trans1))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM