Java sorting method How to use sort

Source: Internet
Author: User

Sort an array:

Sorts the array public void ArraySort () {int[] arr = {1,4,6,333,8,2}; Arrays.sort (arr);//Use the Java.util.Arrays object's Sort method for (int i=0;i<arr.length;i++) {System.out.println (arr[i]);}}

To sort the collection:

Sorts the list in ascending order 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);//Use Collections's Sort method for (int a:list) {System.out.println (a);}} Sort list Descending 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;}}); /Use the Sort method of collections, and override the Compare method for (int a:list) {System.out.println (a);}}
Note: The sort method of collections is sorted by default in ascending order, and you need to override the Conpare method if you need to sort in descending order

  

  

Java sorting method How to use sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.