Anksmonani
Anksmonani

Reputation: 75

How to sort only a specific portion of a List?

I have a List of doubles in java and i want a result list with sorted with specific index in ascending order.

List<Double> DList=new ArrayList();

testList.add(0.5);
testList.add(0.2);
testList.add(0.9);
testList.add(0.1);
testList.add(0.1);
testList.add(0.1);
testList.add(0.54);
testList.add(0.71);
testList.add(0.71);
testList.add(0.71);
testList.add(0.92);
testList.add(0.12);
testList.add(0.65);
testList.add(0.34);
testList.add(0.62);
testList.add(0.5);
testList.add(0.2);
testList.add(0.9);
testList.add(0.1);
testList.add(0.1);
testList.add(0.1);
testList.add(0.54);

I have to perform sorting from index 7. how can i do that?

Upvotes: 3

Views: 1595

Answers (1)

Adam
Adam

Reputation: 36703

  • List.subList(startIndex, endIndex) creates a "backed" collection which sees your original list, aka "proxy" I think.
  • Collections.sort() will just sort the sub-list, any swaps will actually occur in the original list

The JavaDoc explains this more clearly than I can manage:

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list

list.subList(from, to).clear();

Example using your original problem

List<Double> list = new ArrayList<Double>();
list.add(0.5);
list.add(0.2);
list.add(0.9);
list.add(0.1);
list.add(0.1);
list.add(0.1);
list.add(0.54);
list.add(0.71);
list.add(0.71);
list.add(0.71);
list.add(0.92);
list.add(0.12);
list.add(0.65);
list.add(0.34);
list.add(0.62);
list.add(0.5);
list.add(0.2);
list.add(0.9);
list.add(0.1);
list.add(0.1);
list.add(0.1);
list.add(0.54);
Collections.sort(list.subList(7, list.size()));

Upvotes: 10

Related Questions