google / guava

Google core libraries for Java
Apache License 2.0
50.26k stars 10.91k forks source link

Support for trees and traversals #174

Closed gissuebot closed 10 years ago

gissuebot commented 10 years ago

Original issue created by jvdneste on 2009-05-25 at 02:34 PM


As a suggestion; I find it quite useful!

/*  * returns a depth-first iterator for a tree of T  * @param f a function that returns the children of node of the tree  * @param root The root element of the tree  * @return  / public static <T> Iterable<T> walk(final T root,     final Function<? super T, ? extends Iterable<? extends T>> getChildren) {   final Function<T, Iterable<? extends T>> walkFunc =       new Function<T, Iterable<? extends T>>() {     public Iterable<? extends T> apply(final T from) {       return walk(from, getChildren, this);     }   };   return walk(root, getChildren, walkFunc); }

private static <T> Iterable<T> walk(final T root,   final Function<? super T, ? extends Iterable<? extends T>> getChildren,     final Function<T, Iterable<? extends T>> walkFunction) {   return Iterables.concat(     Collections.singleton(root),     Iterables.concat(       Iterables.transform(         getChildren.apply(root),         walkFunction))); }

And a shortcut in case the nodes implement Iterable:

@SuppressWarnings("unchecked") public static <T extends Iterable<T>> Iterable<T> walk(final T root) {   return walk(root, Functions.identity(), WalkIterableFunction.INSTANCE); }

@SuppressWarnings("unchecked") private static enum WalkIterableFunction implements Function {   INSTANCE;

  public Object apply(final Object from) {     return walk(from, Functions.identity(), this);   } };

gissuebot commented 10 years ago

Original comment posted by ray.a.conner on 2014-03-05 at 03:28 AM


I just wanted to say I finally migrated my graph library to use TreeTraverser with Louis's suggestion of using TreeTraverser<Walk<T>> for maintaining paths during the traversal. It works without any unexpected problems, and was a bit cleaner than what I had been doing previously; so thanks. The only dissonance remaining is that is that I'm using something named TreeTraverser for general graph traversals, but I can live with that.