Java:sort从索引到索引的列表

Nub*_*bok 5 java arrays sorting list

对于数组,有一个特殊的函数用于将数组的一部分从索引排序到索引:

Arrays.sort(Object[] a, int fromIndex, int toIndex)

对于 List< T>

还有一个排序功能

Collections.sort(List<T> list)

不幸的是,没有变体接受fromIndex和toIndex参数.

我知道我可以通过应用来解决这个问题

  • 将List转换为数组并应用Arrays.sort,然后将其转换回List
  • 将fromIndex索引的列表条目复制到toIndex到新列表(通过使用list.subList(fromIndex, toIndex)),对其进行排序并覆盖旧列表条目

但我希望有一个更漂亮的方法来做到这一点.

Ada*_*dam 10

只需使用.subList()将"支持"视图放到主列表中,然后调用sort.子列表是"直写",因此更改会反映在原始文件中.

List<Integer> foo = Arrays.asList(5,3,1,6,2,1);
Collections.sort(foo.subList(0, 3)); // sort first 3 elements 
System.out.println(foo);
Collections.sort(foo.subList(3, 6)); // sort last 3 elements
System.out.println(foo);
Run Code Online (Sandbox Code Playgroud)

产量

[1, 3, 5, 6, 2, 1]
[1, 3, 5, 1, 2, 6]
Run Code Online (Sandbox Code Playgroud)