Issue
Say, I've got a class called DomainObject,
class DomainObject {
private Long id;
private String domainParam;
}
I am recieving list of object like:
(id, domainType) = (1, "A") , (1, "B"), (3, "C"), (4, "A"), (1, "C")
After all, I want to receive ImmutableMap with Key(ImmutableList of Id) and Pair(Immutable list of domainParam) like:
1 [A, B, C]
3 [C]
4 [A]
Now I am receiving something like:
{[1]=[DomainObject(id=1, domainParam=A), DomainObject(id=1, domainParam=B), DomainObject(id=1, domainParam=B)]}
And it's not desirable solution.
So far I have a code like:
ImmutableMap<ImmutableList<Long>, ImmutableList<DomainObject>> groupedDomainObject(
List<DomainObject> domainObjectList) {
return domainObjectList.stream()
.collect(
Collectors.collectingAndThen(
Collectors.groupingBy(
(domainObject) -> ImmutableList.of(domainObject.getId()),
ImmutableList.<DomainObject>toImmutableList()),
ImmutableMap::copyOf));
}
I am close to reaching a goal but how I can flat stream value from this part:
ImmutableList.<DomainObject>toImmutableList()
to receive the only domainParam without DomainObject id.
I'll be grateful for any help I can get.
Solution
......
.stream()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(
x -> ImmutableList.of(x.getId()),
Collectors.mapping(
DomainObject::getDomainParam,
ImmutableList.toImmutableList())),
ImmutableMap::copyOf
));
Answered By - Eugene
Answer Checked By - Robin (JavaFixing Admin)