Sorting a part of Java ArrayList

后端 未结 2 517
情深已故
情深已故 2020-12-14 07:38

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.

相关标签:
2条回答
  • 2020-12-14 07:56
    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.

    0 讨论(0)
  • 2020-12-14 08:07

    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.

    0 讨论(0)
提交回复
热议问题