Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a sub-List, Java [duplicate]

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?

like image 990
Adam Avatar asked Jun 28 '26 14:06

Adam


1 Answers

Simple - use subList:

data.subList(start, end).sort(Comparator.naturalOrder())
like image 56
Boris the Spider Avatar answered Jul 01 '26 03:07

Boris the Spider