Deepika
Deepika

Reputation: 95

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

I have a list of java objects as below:

[
  {
    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"
  }
]

How can I convert this into a Map<String, Map<String, String>> like below:

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

I am new to java and below is my code but the code is not correct:

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

                )))

where Translations is proto buffer message like below:

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

Here map<string, string> translations means map like "key1", "This is the deutsch translation"...like this.

Upvotes: 2

Views: 208

Answers (2)

mightyWOZ
mightyWOZ

Reputation: 8335

If you want to do it without using streams then

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);
    }
}

Upvotes: 0

Eran
Eran

Reputation: 393841

The output should be 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)));

I added a merge function, in case there are duplicate keys.

Upvotes: 2

Related Questions