Java collection framework for custom sorting

Source: Internet
Author: User
Tags comparable

The Java Collection Framework provides a variety of sorting methods for different data structures, although many times we can sort by ourselves, such as arrays, but the flexibility of using the ordering method provided by the JDK can improve development efficiency, and usually the implementation of the JDK is more optimized than the performance of its own wheels.

First, using arrays to sort the array

The Java API's description of the arrays class is that this class contains various methods for manipulating arrays, such as sorting and searching.

1, use arrays sort: Arrays use is very simple, directly call sort () can

       int[] arr = new int[] {5,8,-2,0,10};         Arrays.sort (arr);         for (int i=0;i<arr.length;i++) {             System.out.print (arr[i]+ ",");         }                          char[] Chararr = new char[] {' B ', ' A ', ' C ', ' d ', ' d '};         Arrays.sort (Chararr);         for (int i=0;i<arr.length;i++) {             System.out.print (chararr[i]+ ",");         

If you need to sort in descending order, sort in ascending order:Collections.reverse (Arrays.aslist (arr));

2, the realization of Arrays.sort ()

Viewing the source code will find that Arrays.sort () has many overloaded methods, such as sort (int[] a), sort (long[] a), sort (char[] a), etc.

public static void sort (int[] a) {        dualpivotquicksort.sort (a);    

But in the end it is called Dualpivotquicksort.sort (a) method, which is an improved fast sorting, using the multi-way fast sorting method, better performance than the single-way fast sorting method, and depending on the length of the array will eventually choose a different sort implementation, look at the implementation of this method, This does not unfold:

public static void sort (char[] a) {sort (A, 0, a.length-1); } public static void sort (char[] A, int. left, int.) {//Use counting sort on large arrays if (              Right-left > Counting_sort_threshold_for_short_or_char) {int[] count = new Int[num_char_values];                 for (int i = left-1; ++i <= right;             count[a[i]]++); for (int i = num_char_values, k = right + 1; k > left;)                 {while (count[--i] = = 0);                 Char value = (char) i;                  int s = count[i];                 do {a[--k] = value;             } while (--s > 0);         }} else {//use Dual-pivot Quicksort in small arrays dosort (a, left, right); }} private static void Dosort (char[] A, int left, int. right) {//Use Quicksort on small arrays if ( Right-left < Quicksort_threshold) {sort (a, left, Right, true);         Return     }

Ii. using comparator or comparable for custom sorting

In the collection framework, the Collections tool class supports two sorting methods:

Collections.sort (list<t> List); Collections.sort (list<t> List, comparator<? Super T> C)

If the list to be sorted is a number or a character, you can directly use Collections.sort (list), and when the set or array that needs to be sorted is not a purely numeric type, you need to define the collation yourself to implement a comparator comparer.

Here's a look at the applications of comparable and comparator.

Comparable is a sort interface, and a class implements the comparable interface, which means that the class supports sorting.

Comparable is defined as follows:

Public interface Comparable<t> {public     int compareTo (T o);}

the size of x and Y is compared by X.compareto (y) in the interface. returning a negative number means that x is smaller than Y, and returns zero, which means x equals Y, and a positive number means X is greater than Y.

Of course here the meaning of greater than or less than is to be understood according to our collation .

Comparator is the comparator interface, if you need to control the order of a class, and the class itself does not implement the comparable interface, that is, do not support sorting, then you can establish a class to implement the comparator interface, in this interface to establish a specific collation,
The comparator interface is defined as follows:

Public interface comparator<t> {     int compare (t O1, T O2);     Boolean equals (Object obj); }

a comparator class to implement the comparator interface must implement the CompareTo (t O1, T O2) function, and if not necessary, you can not rewrite the Equals () function. because the Equals (object obj) function method has been implemented in the object class.

The int compare (t O1, T O2) is similar to the above X.compareto (y), which returns a positive number after the collation is defined, with 0 and negative numbers representing greater than, equal to, and less than.

Third, how to sort the key or value of HashMap

HashMap as the kay-value structure, itself is unordered, the sort is more flexible, usually through a list to save. The following code sorts the key and value for HashMap, providing several ideas for implementation:

1. Convert to key array, sort by key

object[] Key_arr = Hashmap.keyset (). ToArray ();    Arrays.sort (Key_arr);    For  (object Key:key_arr) {         Object value = Hashmap.get (key);     

2. Sort the value of HashMap

public class Hashmapsort {public static void main (string[] args) {hashmap<string, integer> map = new have             Hmap<string, integer> () {{put ("Tom", 18);             Put ("Jack", 25);             Put ("Susan", 20);         Put ("Rose", 38);                   }};          Valuecomparator cmptor = new Valuecomparator (map); /** * Convert to ordered TREEMAP for output */treemap<string, integer> sorted_map = new treemap<string, in         Teger> (Cmptor);                   Sorted_map.putall (map);         For (String Sortedkey:sorted_map.keySet ()) {System.out.println (Sortedkey+map.get (Sortedkey)); }/** * Convert to ordered List to sort */list<string> keys = new Arraylist<string> (Map.keys         ET ());         Collections.sort (keys, cmptor);         for (String Key:keys) {System.out.println (Key+map.get (key)); }} Static class Valuecomparator implements comparator<string&Gt         {hashmap<string, integer> base_map;         Public Valuecomparator (hashmap<string, integer> base_map) {this.base_map = Base_map; } public int Compare (string arg0, string arg1) {if (!base_map.containskey (arg0) | | |!base_map.contains             Key (arg1)) {return 0;             }//According to value from small to large sort if (Base_map.get (arg0) < Base_map.get (arg1)) {return-1;             } else if (Base_map.get (arg0) = = Base_map.get (arg1)) {return 0;             } else {return 1; }         }     } }

Java collection framework for custom sorting

Related Article

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.