SortingHierarchicalCollections { public List<T> sortFromLeafToRoot(Collection<T> elements) throws CycleDetectedException { return Lists.reverse(sortFromRootToLeaf(elements)); } SortingHierarchicalCollections(Function<T, IdT> index,
                                  Function<T, Optional<IdT>> parentId); List<T> sortFromRootToLeaf(Collection<T> elements); List<T> sortFromLeafToRoot(Collection<T> elements);  }
@Test public void sortFromLeafToRootShouldReturnOrderedMailbox() { Mailbox inbox = Mailbox.builder().name("INBOX").id(INBOX_ID).build(); Mailbox a = Mailbox.builder().name("A").id(A_ID).parentId(INBOX_ID).build(); Mailbox b = Mailbox.builder().name("B").id(B_ID).parentId(INBOX_ID).build(); Mailbox c = Mailbox.builder().name("C").id(C_ID).parentId(B_ID).build(); Mailbox d = Mailbox.builder().name("D").id(D_ID).parentId(A_ID).build(); Mailbox e = Mailbox.builder().name("E").id(E_ID).parentId(C_ID).build(); ImmutableList<Mailbox> input = ImmutableList.of(b, c, d, a, inbox, e); List<Mailbox> result = sut.sortFromLeafToRoot(input); assertThat(result).extracting(Mailbox::getName).endsWith("INBOX").startsWith("E"); }
@Test public void sortFromLeafToRootEmptyMailboxShouldReturnEmpty() { ImmutableList<Mailbox> input = ImmutableList.of(); List<Mailbox> result = sut.sortFromLeafToRoot(input); assertThat(result).isEmpty(); }
@Test public void sortFromLeafToRootOrphanMailboxesShouldReturnInput() { Mailbox a = Mailbox.builder().name("A").id(A_ID).build(); Mailbox b = Mailbox.builder().name("B").id(B_ID).build(); Mailbox c = Mailbox.builder().name("C").id(C_ID).build(); ImmutableList<Mailbox> input = ImmutableList.of(a, b, c); List<String> result = sut.sortFromLeafToRoot(input).stream() .map(Mailbox::getName) .collect(Collectors.toList()); assertThat(result).containsExactly("C", "B", "A"); }
@Test(expected = CycleDetectedException.class) public void sortFromLeafToRootWithLoopShouldThrow() { Mailbox a = Mailbox.builder().name("A").id(A_ID).parentId(B_ID).build(); Mailbox b = Mailbox.builder().name("B").id(B_ID).parentId(A_ID).build(); ImmutableList<Mailbox> input = ImmutableList.of(a, b); sut.sortFromLeafToRoot(input); }