Using forEach to get a list

81 views
Skip to first unread message

Victor

unread,
Sep 15, 2011, 11:29:22 AM9/15/11
to lambdaj
Hi, I'm using lambdaj for a few days now but I'm having some trouble
to do this (pseudo-code):

class A {

Object object;

List<AnotherObject> list;

}

for (Group<A> aGroup : group(aList,
by(on(A.class).getObject())).subgroups()) {

for (Object o : forEach(aGroup.findAll()).getObject()) {
// Ok, this works!
}

for (AnotherObject ao : /* How to get it? */
forEach(aGroup.findAll()).getList()) {
// *** This for raises this exception: java.lang.ClassCastException:
java.util.ArrayList cannot be cast to com.foo.AnotherObject ***
}

}

Please, how can I get the values from list? Or... what's the correct
way to do this?

Thanks!

Victor (Brazil)

Mario Fusco

unread,
Sep 15, 2011, 1:43:30 PM9/15/11
to lam...@googlegroups.com
Since aGroup.findAll() is a List<A> and for each A a.getList returns a List<AnotherObject> what forEach(aGroup.findAll()).getList() actually returns is a List<List<AnotherObject>>.
You could flatten this nested list with the flatten() method so the following should work:

for (AnotherObject ao : flatten(forEach(aGroup.findAll()).getList())) { ... }

Let me know if this solves your issue.
Cheers,
Mario

Victor

unread,
Sep 15, 2011, 2:05:14 PM9/15/11
to lambdaj
Thanks for the answer, Mario!

Yes, this method works, but I have to cast it's type, since I get as a
object.

for (Object o : flatten(forEach(aGroup.findAll()).getList())) {

AnotherObject ao = (AnotherObject) o;
// ...

}

At the source code, the flatten function is defined by:

public static <T extends Object> List<T> flatten(Object iterable) {


But the collect has two definitions:

public static <T extends Object> List<? extends T> collect(Object
iterable) {
public static <T extends Object> List<T> collect(Object iterable, T
argument) {

Can you provide the argument variable to flatten function too?

Anyway, it worked!

Thanks,

Victor
Reply all
Reply to author
Forward
0 new messages