Created
April 11, 2022 16:20
-
-
Save elarif/04d6069fcbf36b9a73695642c0731b41 to your computer and use it in GitHub Desktop.
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
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); | |
} |
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
First step (easy)
We want to be able to build simple Trees like this :