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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this is a correct answer. Collections.sort does the sorting in place and List.subList returns a list that is backed by the original list.
There is a fencepost error in this solution, as this command will actually exclude the element in index 3.
6

use the subList [inherited from AbstractList] method in ArrayList. And then use Collections.sort() on that sub-list. That is if writing a highly optimised custom sort function is truly hard work.

4 Comments

While "inherited from AbstractList" is not wrong, as such, it's mostly irrelevant. It's more important that subList is defined by List, in my opinion.
AFAIK, List does NOT define subList. Hence, the relevance of letting the OP know where exactly does ArrayList inherit that behaviour from.
@anirvan Sure it does.
@TavianBarnes List is an interface, so what I was merely implying is that it doesn't implement it, while AbstractList does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.