Java Collections.sort()方法及实例

Java Collections.sort()方法及实例

java.util.Collections.sort() 方法存在于java.util.Collections类中。它用于将指定的集合列表中的元素按升序排序。它的工作原理类似于java.util.Arrays.sort()方法,但它比它更好,因为它可以对数组中的元素进行排序,也可以对链接列表、队列和许多其他元素进行排序。

public static void sort(List myList)
Java

myList : 一个我们想要排序的列表类型对象。

该方法不返回任何东西

例子。

Let us suppose that our list contains
{"Geeks For Geeks", "Friends", "Dear", "Is", "Superb"}

After using Collection.sort(), we obtain a sorted list as
{"Dear", "Friends", "Geeks For Geeks", "Is", "Superb"}
Java

以升序对数组列表进行排序

// Java program to demonstrate working of Collections.sort()
import java.util.*;
 
public class Collectionsorting
{
    public static void main(String[] args)
    {
        // Create a list of strings
        ArrayList<String> al = new ArrayList<String>();
        al.add("Geeks For Geeks");
        al.add("Friends");
        al.add("Dear");
        al.add("Is");
        al.add("Superb");
 
        /* Collections.sort method is sorting the
        elements of ArrayList in ascending order. */
        Collections.sort(al);
 
        // Let us print the sorted list
        System.out.println("List after the use of" +
                        " Collection.sort() :\n" + al);
    }
}
Java

输出

List after the use of Collection.sort() :
[Dear, Friends, Geeks For Geeks, Is, Superb]
Java

时间复杂度 :O(N log N),因为Collections.sort()的时间复杂度是O(nlog(n))。
辅助空间 :O(1)

对ArrayList进行降序排序

// Java program to demonstrate working of Collections.sort()
// to descending order.
import java.util.*;
 
public class Collectionsorting
{
    public static void main(String[] args)
    {
        // Create a list of strings
        ArrayList<String> al = new ArrayList<String>();
        al.add("Geeks For Geeks");
        al.add("Friends");
        al.add("Dear");
        al.add("Is");
        al.add("Superb");
 
        /* Collections.sort method is sorting the
        elements of ArrayList in ascending order. */
        Collections.sort(al, Collections.reverseOrder());
 
        // Let us print the sorted list
        System.out.println("List after the use of" +
                        " Collection.sort() :\n" + al);
    }
}
Java

输出

List after the use of Collection.sort() :
[Superb, Is, Geeks For Geeks, Friends, Dear]
Java

时间复杂度: O(N log N),因为Collections.sort()的时间复杂度是O(nlog(n))。
辅助空间: O(1)

根据用户定义的标准对ArrayList进行排序 我们可以使用比较器接口来实现这一目的。

// Java program to demonstrate working of Comparator
// interface and Collections.sort() to sort according
// to user defined criteria.
import java.util.*;
import java.lang.*;
import java.io.*;
 
// A class to represent a student.
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;
    }
 
    // Used to print student details in main()
    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;
    }
}
 
// Driver class
class Main
{
    public static void main (String[] args)
    {
        ArrayList<Student> ar = new ArrayList<Student>();
        ar.add(new Student(111, "bbbb", "london"));
        ar.add(new Student(131, "aaaa", "nyc"));
        ar.add(new Student(121, "cccc", "jaipur"));
 
        System.out.println("Unsorted");
        for (int i=0; i<ar.size(); i++)
            System.out.println(ar.get(i));
 
        Collections.sort(ar, new Sortbyroll());
 
        System.out.println("\nSorted by rollno");
        for (int i=0; i<ar.size(); i++)
            System.out.println(ar.get(i));
    }
}
Java

输出

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc
Java

Arrays. sort() vs Collections.sort() Arrays.sort适用于数组,也可以是原始数据类型。Collections.sort()适用于对象集合,如ArrayList、LinkedList等。我们可以使用Collections.sort()在给定数组项目创建ArrayList后对数组进行排序。

// Using Collections.sort() to sort an array
import java.util.*;
public class Collectionsort
{
    public static void main(String[] args)
    {
        // create an array of string objs
        String domains[] = {"Practice", "Geeks",
                            "Code", "Quiz"};
 
        // Here we are making a list named as Collist
        List colList =
            new ArrayList(Arrays.asList(domains));
 
        // Collection.sort() method is used here
        // to sort the list elements.
        Collections.sort(colList);
 
        // Let us print the sorted list
        System.out.println("List after the use of" +
                        " Collection.sort() :\n" +
                        colList);
    }
}
Java

输出

List after the use of Collection.sort() :
[Code, Geeks, Practice, Quiz]
Java

Arrays.sort() vs Collections.sort() 的时间复杂度

Arrays.sort()使用Dual-Pivot Quicksort算法,其时间复杂度为O(N.log N),通常比传统Quicksort算法快。另一方面,Collections.sort()创建了一个列表元素的数组,使用自适应的Mergesort算法对它们进行排序,并在列表上进行迭代,将每个元素放在正确的位置。因此,对于原始数据类型如int、char、double等。Arrays.sort()被证明比Collections.sort()更节省时间。涉及原始数据类型的问题应该尝试使用Arrays.sort()来解决,以达到更好的优化效果。

下面的代码展示了这一区别。

/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main (String[] args) {
        int len = 5000000;
       
          // creating a large test array
        int[] arr = new int[len];
        for (int i = len; i > 0; i--)
            arr[len - i] = i;
       
          // creating a large test arraylist
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = len; i > 0; i--)
            list.add(i);
         
          // calculating time used by arrays.sort()
        long startA = System.currentTimeMillis();
        Arrays.sort(arr);
        long stopA = System.currentTimeMillis();
         
          // calculating time used by collections.sort()
          long startAL = System.currentTimeMillis();
          Collections.sort(list); 
        long stopAL = System.currentTimeMillis();
         
          System.out.println("Time taken by Arrays.sort(): " + (stopA - startA));
        System.out.println("Time taken by Collections.sort(): " + (stopAL - startAL));
    }
}
 
// This code is contributed by godcoder28
Java

输出

Time taken by Arrays.sort(): 29
Time taken by Collections.sort(): 42
Java

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册