gpt4 book ai didi

java - 如何将 Java 对象列表转换为 Map>

转载 作者:行者123 更新时间:2023-12-04 07:22:08 26 4
gpt4 key购买 nike

我有一个 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 ...像这样。

最佳答案

输出应该是 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)));
我添加了一个合并功能,以防有重复的键。

关于java - 如何将 Java 对象列表转换为 Map<String, Map<String, String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68426856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com