Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert list of payloads with a property List<String> to HashMap<String, Payload)

I’ve a list of payloads and a payload looks like

Payload {
 public int id;
 public String name;
 public String foo;
 public List<String> list;
}

now I want this to a HashMap where the key is a value of the list property, like

payloads = [
 {id:45, name:"Alfred", foo:"bar", list:["AAA", "BBB"]},
 {id:2, name:"John", foo:"various", list:["CCC", "DDD"]},
 ...
];

to HashMap<String, Payload>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

map = [
{key: "AAA", value: {id:45, name:"Alfred", foo:"bar", list:["AAA", "BBB"]},
{key: "BBB", value: {id:45, name:"Alfred", foo:"bar", list:["AAA", "BBB"]},
{key: "CCC", value: {id:2, name:"John", foo:"various", list:["CCC", "DDD"]},,
{key: "DDD", value: {id:2, name:"John", foo:"various", list:["CCC", "DDD"]},,
]

I’ve tried .flatMap() and own mapping collectors but nothing worked. If I research I only find solutions to group by flat payload objects, like Payload.name nothing if the group key is in a List of these objects.

Any ideas?

>Solution :

Assume given List<Payload> payloads with stream API it could be done as follows:

    payloads.stream().flatMap(payload ->
            payload.list.stream().map(listValue -> Map.entry(listValue, payload))
    ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Although, it may be worthy to use @Jorn approach

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading