Skip to content

Instantly share code, notes, and snippets.

@jnape
Created April 22, 2012 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnape/2466342 to your computer and use it in GitHub Desktop.
Save jnape/2466342 to your computer and use it in GitHub Desktop.
Aggregate List of all ancestors for a particular type in Java, using foldLeft and recursion
package example;
import com.jnape.dynamiccollection.lambda.Accumulator;
import com.jnape.dynamiccollection.list.DynamicList;
import java.util.List;
import static com.jnape.dynamiccollection.DynamicCollectionFactory.list;
public class Example {
public static List<Class> getAncestors(Class type) {
DynamicList<Class> types = list(type.getInterfaces())
.concat(list(type.getClasses()))
.concat(list(type.getSuperclass()).without(null))
.unique();
return types.foldLeft(types, new Accumulator<DynamicList<Class>, Class>() {
@Override
public DynamicList<Class> apply(DynamicList<Class> types, Class type) {
if (type.equals(Object.class))
return types;
return types.concat(getAncestors(type));
}
}).unique();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment