Java – how do I use group mapping streams?

I have a long child

// ordered by parent.id / child.id
Stream<Child> childStream;

Say,

Child(id = 1,parent(id = 1))
Child(id = 2,parent(id = 1))
Child(id = 3,parent(id = 2))
Child(id = 4,parent(id = 2))
Child(id = 5,parent(id = 3))

Every child has parents

class Child {
    Parent parent;
}

Now, how do I map the flow to the family flow?

class Family {
    Parent parent;
    List<Child> children;
}

I already know collectors Groupingby, but the stream is very long, so it is not applicable to collect them all into the map

Solution

If streams are sorted by parent (ID), then this is the streamex solution

StreamEx.of(childStream)
        .collapse((a,b) -> a.getParent().getId() == b.getParent().getId(),Collectors.toList())
        .map(cl-> new Family(cl.get(0).getParent(),cl))...;

Crash is a lazy evaluation of groupy For example, if you only want to get the first five families, only the children in the first five families will be loaded, not all

StreamEx.of(childStream)
        .collapse((a,cl))
        .limit(5);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>