class 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);
                    // There is an edge from right to left, so we need to move left element after right
                    if (hasEdge.apply(from, to) && i > j) {
                        result.remove(j);
                        result.add(i, to);
                        return result;
                    }
                }
            }
        }
        return result;
    }

}