Skip to content

Instantly share code, notes, and snippets.

@elarif
Created April 11, 2022 16:20
Show Gist options
  • Save elarif/04d6069fcbf36b9a73695642c0731b41 to your computer and use it in GitHub Desktop.
Save elarif/04d6069fcbf36b9a73695642c0731b41 to your computer and use it in GitHub Desktop.
public interface Tree<T> {
T value();
List<Tree<T>> children();
Optional<Tree<T>> parent();
List<T> childrenValues(final T value);
List<T> parentValues(final T value);
}
@elarif
Copy link
Author

elarif commented Apr 26, 2022

First step (easy)

static <T> Tree<T> of(final T value) {
// TODO
}
static <T> Tree<T> of(final T value, final List<Tree<T>> children) {
// TODO
}

static <T> Tree<T> of(
      final T value, 
      final List<Tree<T>> children, 
      final Optional<Tree<T>> parent) {
// TODO
  }

We want to be able to build simple Trees like this :

Tree.of(1); // parent and children are Optional.empty and Collections.emptyList()
Tree.of(1, Arrays.asList(Tree.of(2), Tree.of(3))); // parent is Optional.empty
Tree.of(1, Arrays.asList(Tree.of(2), Tree.of(3)), Optional.of(Tree.of(0)));

@elarif
Copy link
Author

elarif commented Apr 26, 2022

second step (harder)

static <T, ID> List<Tree<T>> of(
      final Collection<T> source,
      final Function<T, ID> idMapper,
      final Function<T, Optional<ID>> parentMapper) {
      // TODO
}

We want to avoid having to build complex trees by hand using the static methods from easy step.

    final List<Integer> source = IntStream.range(1,50).boxed().collect(Collectors.toList());
    final Function<Integer, Integer> idMapper = Function.identity();
    final Function<Integer, Optional<Integer>> parentMapper = i -> i > 1 ? Optional.of((int) Math.sqrt(i)):Optional.empty();
    Tree tree = Tree.of(source, idMapper, parentMapper);

tree should look like this :
1
├──2
│ ├──4
│ │ ├──16
│ │ ├──17
│ │ ├──18
│ │ └──19
│ ├──5
│ ├──6
│ ├──7
│ └──8
└──3
├──9
├──10
├──11
├──12
├──13
├──14
└──15

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