2

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?

retrodrone
  • 5,850
  • 9
  • 39
  • 65

2 Answers2

6

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.

retrodrone
  • 5,850
  • 9
  • 39
  • 65
1

I found @retrodone 's answer not so easy to understand. Here's another example:

List<String> lista1 = Arrays.asList(new String[]{"1", "2", "3"});
List<String> lista2 = Arrays.asList(new String[]{"4", "5", "6"});

Bla bla1 = new Bla(lista1);
Bla bla2 = new Bla(lista2);

List<Bla> blas = Lists.newArrayList(bla1, bla2);

System.out.println(flatten(collect(blas , on(Bla.class).getLista())));
Clint Eastwood
  • 4,995
  • 3
  • 31
  • 27