GraphExt { public static <T> List<T> order(List<T> nodes, BiFunction<T, T, Boolean> hasEdge) { List<T> result = new ArrayList<>(nodes); for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes.size(); j++) { if (i != j) { T from = nodes.get(i); T to = nodes.get(j); if (hasEdge.apply(from, to) && i > j) { result.remove(j); result.add(i, to); return result; } } } } return result; }  static List<T> order(List<T> nodes, BiFunction<T, T, Boolean> hasEdge);  }
@Test public void testOrdering() throws Exception { List<Character> ordered = GraphExt.order(Arrays.asList('A', 'B', 'C'), (s1, s2) -> s1 == 'A' && s2 == 'C'); assertThat(ordered).containsExactlyInAnyOrder('A', 'B', 'C'); List<Character> notOrdered = GraphExt.order(Arrays.asList('A', 'B', 'C'), (s1, s2) -> s1 == 'C' && s2 == 'A'); assertThat(notOrdered).containsExactlyInAnyOrder('B', 'C', 'A'); }