繁体   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