Skip to content

Instantly share code, notes, and snippets.

@pfichtner
Last active February 16, 2018 19:34
Show Gist options
  • Select an option

  • Save pfichtner/21b9ae1a4bd98a33d7318aff276990ef to your computer and use it in GitHub Desktop.

Select an option

Save pfichtner/21b9ae1a4bd98a33d7318aff276990ef to your computer and use it in GitHub Desktop.
Java 8: Tree Stream of parent tree nodes
package java8tree;
import java8tree.data.FooBar;
import java8tree.data.TreeNode;
public class Legacy {
public FooBar findFooBar(TreeNode selection) {
FooBar foobar = null;
if (istFooBar(selection.getParentPath())) {
foobar = (FooBar) selection.getParentPath().getLastPathComponent().getModel();
} else if (istFooBar(selection.getParentPath().getParentPath())) {
foobar = (FooBar) selection.getParentPath().getParentPath().getLastPathComponent().getModel();
} else if (istFooBar(selection.getParentPath().getParentPath().getParentPath())) {
foobar = (FooBar) selection.getParentPath().getParentPath().getParentPath().getLastPathComponent().getModel();
}
return foobar;
}
private boolean istFooBar(TreeNode parentPath) {
return parentPath.getLastPathComponent().getModel() instanceof FooBar;
}
}
package java8tree;
import java8tree.data.FooBar;
import java8tree.data.Model;
import java8tree.data.TreeNode;
public class LegacyToJava7 {
public FooBar findFooBar(TreeNode selection) {
for (TreeNode current = selection; current != null; current = current.getParentPath()) {
Model lastPath = extractLastpath(current);
if (lastPath instanceof FooBar) {
return (FooBar) lastPath;
}
}
return null;
}
private static Model extractLastpath(TreeNode parentPath) {
return parentPath.getLastPathComponent().getModel();
}
}
package java8tree;
import static java.util.stream.Stream.concat;
import static java.util.stream.Stream.empty;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java8tree.data.FooBar;
import java8tree.data.PathComponent;
import java8tree.data.TreeNode;
public class LegacyToJava8Generic2 {
public FooBar findFooBar(TreeNode selection) {
// alternative: (POFooBar) ... instead of .map(POFooBar.class::cast)
return streamOf(selection, TreeNode::getParentPath) //
.map(TreeNode::getLastPathComponent) //
.map(PathComponent::getModel) //
.filter(FooBar.class::isInstance) //
.map(FooBar.class::cast) //
.findFirst().orElse(null);
}
private static <T> Stream<T> streamOf(T t, Function<T, T> function) {
return streamOf(t, function, Objects::isNull);
}
public static <T> Stream<T> streamOf(T t, Function<T, T> f, Predicate<T> p) {
return p.test(t) ? empty() : concat(Stream.of(t), Stream.of(t).flatMap(n -> streamOf(f.apply(n), f, p)));
}
}
@tobibechtold
Copy link
Copy Markdown

Java Porn ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment