Overall your method is neat, and well structured. I can't really fault it, given the constraints of the problem.
Update: Actually, the method should have a lower-case 's' to start the name. How did I miss that the first time? Should be splitCollection
not SplitCollection
I would prefer that the method declared the input col
as final
: public static <E> ArrayList<Collection<E>> SplitCollection (final Collection<E> col)
because that is a habit I am in...
A Java 8 implementation of this would be a good exercise.
This is what I would try:
public static <T, U extends Collection<T>, V extends Collection<T>> ArrayList<V> splitCollection (U col, Supplier<V> supplier) {
return col.stream().map(v -> {
V subcol = supplier.get();
subcol.add(v);
return subcol;
}).collect(Collectors.toCollection(ArrayList::new));
}
and it would be used like:
public static void main(String[] args) {
System.out.println("Result:"
+ splitCollection(Arrays.asList("hello","world"), ArrayList::new));
}
which gives the output:
Result:[[hello], [world]]
Note, in the Java 8 example, I allow the sub collection to be any supported type that you can add the content to. So, for the above example, the input is an inaccessible list (no public default constructor), but the supplier gives you what you need.