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

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