Created
April 22, 2012 19:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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