这篇文章主要为大家详细介绍了 Java 排序方法 sort 用法, 对数组集合的排序方法, 具有一定的参考价值, 感兴趣的小伙伴们可以参考一下
对数组的排序:
- // 对数组排序
- public void arraySort(){
- int[] arr = {1,4,6,333,8,2};
- Arrays.sort(arr);// 使用 java.util.Arrays 对象的 sort 方法
- for(int i=0;i<arr.length;i++){
- System.out.println(arr[i]);
- }
- }
对集合的排序:
- // 对 list 升序排序
- public void listSort1(){
- List<Integer> list = new ArrayList<Integer>();
- list.add(1);
- list.add(55);
- list.add(9);
- list.add(0);
- list.add(2);
- Collections.sort(list);// 使用 Collections 的 sort 方法
- for(int a :list){
- System.out.println(a);
- }
- }
- // 对 list 降序排序
- public void listSort2(){
- List<Integer> list = new ArrayList<Integer>();
- list.add(1);
- list.add(55);
- list.add(9);
- list.add(0);
- list.add(2);
- Collections.sort(list, new Comparator<Integer>() {
- public int compare(Integer o1, Integer o2) {
- return o2 - o1;
- }
- });// 使用 Collections 的 sort 方法, 并且重写 compare 方法
- for(int a :list){
- System.out.println(a);
- }
- }
注意: Collections 的 sort 方法默认是升序排列, 如果需要降序排列时就需要重写 conpare 方法
来源: http://www.phperz.com/article/18/0224/358831.html