转-Collections.sort() in Java

Reference:

https://www.geeksforgeeks.org/collections-sort-java-examples/

 

Collections.sort() in Java with Examples

java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.
It works similar to java.util.Arrays.sort() method but it is better then as it can sort the elements of Array as well as linked list, queue and many more present in it.

public static void sort(List myList)

myList : A List type object we want to sort.

This method doesn't return anything

Example:

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"}

Sorting an ArrayList in ascending order



filter_none

edit

play_arrow

brightness_4

// 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);

    }

}

chevron_right

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

Output:

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

 
Sorting an ArrayList in descending order

filter_none

edit

play_arrow

brightness_4

// 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);

    }

}

chevron_right

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

Output:

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

 
Sorting an ArrayList according to user defined criteria.
We can use Comparator Interface for this purpose.

filter_none

edit

play_arrow

brightness_4

// 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));

    }

}

Output :

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

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

Arrays.sort() vs Collections.sort()
Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayListLinkedList, etc.

We can use Collections.sort() to sort an array after creating a ArrayList of given array items.

filter_none

edit

play_arrow

brightness_4

// 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);

    }

}

Output:

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

This article is contributed by Mohit Gupta. Article is wished to be useful to the esteemed Geeks.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
.

Collections.sort() in Java with Examples

java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.
It works similar to java.util.Arrays.sort() method but it is better then as it can sort the elements of Array as well as linked list, queue and many more present in it.

public static void sort(List myList)

myList : A List type object we want to sort.

This method doesn't return anything

Example:

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"}

Sorting an ArrayList in ascending order



filter_none

edit

play_arrow

brightness_4

// 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);

    }

}

chevron_right

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

Output:

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

 
Sorting an ArrayList in descending order

filter_none

edit

play_arrow

brightness_4

// 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);

    }

}

chevron_right

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

Output:

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

 
Sorting an ArrayList according to user defined criteria.
We can use Comparator Interface for this purpose.

filter_none

edit

play_arrow

brightness_4

// 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));

    }

}

Output :

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

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

Arrays.sort() vs Collections.sort()
Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayListLinkedList, etc.

We can use Collections.sort() to sort an array after creating a ArrayList of given array items.

filter_none

edit

play_arrow

brightness_4

// 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);

    }

}

Output:

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

This article is contributed by Mohit Gupta. Article is wished to be useful to the esteemed Geeks.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值