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?
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.
Comments