Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flat ImmutableList in ImmutableMap

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.

like image 878
Martin Avatar asked Oct 22 '25 03:10

Martin


2 Answers

        ......
        .stream()
        .collect(Collectors.collectingAndThen(
            Collectors.groupingBy(
                x -> ImmutableList.of(x.getId()),
                Collectors.mapping(
                    DomainObject::getDomainParam,
                    ImmutableList.toImmutableList())),
            ImmutableMap::copyOf
        ));
like image 87
Eugene Avatar answered Oct 23 '25 18:10

Eugene


ImmutableMap<Long, ImmutableList<String>> groupedDomainObject(
                List<DomainObject> domainObjectList) {

            return domainObjectList
                    .stream()
                    .collect(
                            Collectors.collectingAndThen(
                                Collectors.toMap(
                                    DomainObject::getId,
                                    obj -> ImmutableList.of(obj.domainParam),
                                    (a, b) -> ImmutableList.<String>builder().addAll(a).addAll(b).build()
                                ),
                                ImmutableMap::copyOf
                            )
                    );
        }
like image 35
Swapan Pramanick Avatar answered Oct 23 '25 18:10

Swapan Pramanick