Home > Java > javaTutorial > body text

Detailed explanation of Java sorting method sort usage

高洛峰
Release: 2017-01-17 12:00:04
Original
2091 people have browsed it

The examples in this article share Java's sorting methods for arrays and collections for your reference. The specific content is as follows

Sort arrays:

//对数组排序
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]);
  }
}
Copy after login


Sort the collection:

//对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);
    }
}
Copy after login


Note: The sort method of Collections is arranged in ascending order by default. If you need to sort in descending order, you need to override the compare method

The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support the PHP Chinese website.

For more detailed explanations of Java sorting method sort usage and related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!