Java Collections sort()

sort() 用于对指定列表中存在的元素进行排序。sort()有两个重载方法:

  • Java Collections sort(list) 方法
  • Java Collections sort(list,comp) 方法

1 语法

public static <T extends Comparable<? super T>> void sort(List<T> list)  

或

public static <T> void sort(List<T> list, Comparator<? super T> comp)  

2 参数

list:这是将要排序的列表。

comp:由比较器确定列表的顺序。

3 返回值

4 Collections sort()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.sort的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create an array of string objects
        String str[] = { "Java","Python","Android","One","Ruby","Node.js"};
        //Create list
        List<String> list = new ArrayList<>(Arrays.asList(str));
        System.out.println("Specified value before sort: "+list);
        //Sort the list
        Collections.sort(list);
        System.out.println("Specified value after sort: "+list);
    }
}

输出结果为:

Specified value before sort: [Java, Python, Android, One, Ruby, Node.js]
Specified value after sort: [Android, Java, Node.js, One, Python, Ruby]

5 Collections sort()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.sort的例子
 */
import java.util.*;

public class Demo {

    public static void main (String[] args)
    {
        ArrayList<Student> arr = new ArrayList<Student>();
        arr.add(new Student(101, "Java", "GD"));
        arr.add(new Student(103, "Ruby", "HN"));
        arr.add(new Student(102, "Android", "WH"));
        System.out.println("Data before sorted-");
        for (int i=0; i<arr.size(); i++)
            System.out.println(arr.get(i));
        //Sorting data according to specified comparator
        Collections.sort(arr, new Sortbyroll());
        System.out.println("Data after sorted by rollno-");
        for (int i=0; i<arr.size(); i++)
            System.out.println(arr.get(i));
    }
}
//Class which represents a student data.
class Student
{
    int rollno;
    String name, address;
    //Constructor
    public Student(int rollno, String name, String address)
    {
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
    //Prints student data
    public String toString()
    {
        return this.rollno + " " + this.name + " " + this.address;
    }
}
class Sortbyroll implements Comparator<Student>
{
    //Used for sorting in ascending order of roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}

输出结果为:

Data before sorted-
101 Java GD
103 Ruby HN
102 Android WH
Data after sorted by rollno-
101 Java GD
102 Android WH
103 Ruby HN

 

热门文章

优秀文章