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

504497806:
Dominic

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>

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?

G.Domozhirov

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related