Alex Rivera | Logout

Sorting a part of Java ArrayList

Asked 2011-03-02T08:08:09.423
30

What is the most efficient way of sorting only a part of ArrayList? Say all elements from index 0 to 3 in an Arraylist which contains 10 elements.

Is there a library function available in Java?

Apart from Collections.sort(list) which sorts the entire List!

Writing a highly optimised custom sort function will take some work.

Edit
Report

1 Answer

64

In Java 8+, use List#sort.

list.subList(0,3).sort(null) ;

In earlier Java:

Collections.sort(list.subList(0,3));

Note: '3' here is excluded from sorting.

To quote the documentation:

public List subList(int fromIndex, int toIndex)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

answered 2011-03-02T08:10:58.203

Your Answer