Update: I'm aware of the similarities to Sorting a part of Java ArrayList. This question asks about the List interface rather than the ArrayList class specifically, and as such is more broad. I think it merits a separate question.
In Java, the Arrays class has a static method that allows you to sort a subarray within an array:
public static <T> void sort(
T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
I'd like to sort a List in a similar manner, i.e. I'd like to be able to pass in a fromIndex and a toIndex argument to List's sort method. However, the documentation for List indicates that its sort method only accepts a Comparator. Aside from converting a List to an Array and invoking the Arrays.sort method that accepts a range of elements, what are some good ways to sort a subsection of a List's elements in Java?
Simple - use subList:
data.subList(start, end).sort(Comparator.naturalOrder())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With