Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a part of Java ArrayList

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.

like image 432
Nitish Upreti Avatar asked Mar 02 '11 08:03

Nitish Upreti


People also ask

How do you sort part of an ArrayList?

In order to sort elements in an ArrayList in Java, we use the Collections. sort() method in Java. This method sorts the elements available in the particular list of the Collection class in ascending order. where list is an object on which sorting needs to be performed.

How do you sort elements in an ArrayList using comparable interface?

We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.

How can we sort a list of elements in Java?

Summary. Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

How do I get an element from an ArrayList?

An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.


2 Answers

Collections.sort(list.subList(0,3));  Note: '3' here is excluded from sorting 

It is described in 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.

like image 71
Suraj Chandran Avatar answered Sep 24 '22 03:09

Suraj Chandran


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.

like image 40
anirvan Avatar answered Sep 23 '22 03:09

anirvan