Search code examples
javacollectionslambdaj

How do i combine a list of lists using lambdaj?


I want to be able to combine sublists into a single list using lambdaj.

I have an iterative version that works:

// HDU elements are children of each subsystem
Collection<SpaceSystemType> subsystems = this.getAllSubsystems();
Set<SpaceSystemType> sources = new HashSet<SpaceSystemType>();

// Iterate the subsystems, collecting all the sources
for (SpaceSystemType subsystem : subsystems)
    sources.addAll(subsystem.getSpaceSystem()); // getSpaceSystem returns a List<SpaceSystemType>

return sources;

I'd like to be able to do this:

extract(subsystems, on(SpaceSystemType.class).getSpaceSystem());

But extract returns a

List<List<SpaceSystemType>> 

so I must be using the wrong command.

Which lambdaj command achieves what I want?


Solution

  • I solved this using flatten:

    List<SpaceSystemType> sources = flatten(extract(subsystems, on(SpaceSystemType.class).getSpaceSystem()));
    

    SpaceSystemType is a JAXB-generated class representing a subtree of elements. Since SpaceSystemType.getSpaceSystem() returns a List, it's necessary to direct lambdaj to take all of the leaves from the tree.