Java programming skills: List sorting

Source: Internet
Author: User
Tags collator

The List Implementation defined in the Java Collection framework includes vector, arraylist, and sorted list. These sets provide index access to the object group. They support adding and deleting elements. However, they do not have built-in support for element sorting.

You
You can use the sort () method in the Java. util. Collections class to sort list elements. You can either pass a list object to the method or pass
A list and a comparator. If all the elements in the list are of the same type and the class implements the comparable interface, you can simply call
Collections. Sort (). If this class does not implement comparator, you can also pass a comparator to the method sort () for sorting
. If you do not want to use the default sorting order, you can also pass a comparator to the method sort () for sorting. If not all elements in the list are of the same type
You are not so lucky when sorting. Unless you write a dedicated cross-class comparator.

 
What is the sorting order? If the element is a string object, the sorting order is saved according to character encoding, which is basically the ASCII/Unicode value of each character. If
The limit is generally enough for processing English, but the sort order is saved because it first ranks the A-Z and then the lowercase letter A-Z. However, if you are processing non-English text, or you just want to use different sorting orders
Sample collections. Sort () shows the second change. For example, you want to sort strings in reverse order. To implement this function, you can
Obtain a reverse order comparator through reverseorder. Then, you pass the reverse comparator to the sort () method. In other words
Next work:

List list = ...;
Comparator comp = collections. reverseorder ();
Collections. Sort (list, comp );

 
If the list contains items man, man, woman, and woman, the sorted list will be man, woman, man,
Woman. There is nothing complicated here. Note that collections. Sort () is used for in-situ sorting. If you want to retain the original sequence, you must first
Copy and sort the data, as shown in the following figure:

List list = ...;
List copyoflist = new arraylist (list );
Collections. Sort (copyoflist );

Here, the sorted list is man, woman, man, woman, but the original list (man, man, woman, woman) is retained.

So far, sorting is case sensitive. How do you sort case-insensitive data? One implementation method is to implement comparator as follows:

Public static class caseinsensitivecomparator
Implements comparator {
Public int compare (Object element1,
Object element2 ){
String lower1 =
Element1.tostring (). tolowercase ();
String lower2 =
Element2.tostring (). tolowercase ();
Return lower1.compareto (lower2 );
}
}

You do not need to manually create this class. Instead, you can use the existing comparator, case_insensivtive_order, which is defined in the string class.

This implementation method has a small problem. The sort () algorithm provides stable sorting and maintains the same elements as the original sequence. This means that a list containing two elements "woman" and "woman" will be sorted in different order, which is determined by the order in which the two elements appear in the list.

What if the language is different? The Java. Text package provides the collector and collectionkey classes to sort languages. Here is an example:

NOTE: If your text is in the local language rather than the default language, you need to pass a local language to the getinstance () method, just like:

Public static class collatorcomparator
Implements comparator {
Collator = collator. getinstance ();
Public int compare (Object element1,
Object element2 ){
Collationkey key1 = collator. getcollationkey (
Element1.tostring ());
Collationkey key2 = collator. getcollationkey (
Element2.tostring ());
Return key1.compareto (key2 );
}
}

 
You are sorting the set keywords, not the actual strings. This not only provides fixed case-insensitive sorting, but also supports cross-language sorting. In other words, if you are against Spanish and non-Spanish
Text mixed words for sorting, words Ma? Ana
(Tomorrow) will be placed in front of mantra. If you do not use collector, Ma? Ana will be placed behind mantra.

The following program sorts a list in different types (default, case-sensitive, and language-sensitive ):

Import java. AWT. borderlayout;
Import java. AWT. container;
Import java. Io .*;
Import java. Text .*;
Import java. util .*;
Import javax. Swing .*;

Public class sortit {

Public static class collatorcomparator
Implements comparator {
Collator = collator. getinstance ();
Public int compare (Object element1,
Object element2 ){
Collationkey key1 = collator. getcollationkey (
Element1.tostring ());
Collationkey key2 = collator. getcollationkey (
Element2.tostring ());
Return key1.compareto (key2 );
}
}

Public static class caseinsensitivecomparator
Implements comparator {
Public int compare (Object element1,
Object element2 ){
String lower1 = element1.tostring ().
Tolowercase ();
String lower2 = element2.tostring ().
Tolowercase ();
Return lower1.compareto (lower2 );
}
}

Public static void main (string ARGs []) {
String words [] =
{"Man", "man", "Woman", "Woman ",
"Manana", "Manana", "Ma? Ana "," Ma? Ana ",
"Mantra", "mantra", "mantel", "mantel"
};

// Create frame to display sortings
Jframe frame = new jframe ("sorting ");
Frame. setdefaclocloseoperation (
Jframe. exit_on_close );
Container contentpane = frame. getcontentpane ();
Jtextarea textarea = new jtextarea ();
Jscrollpane pane = new jscrollpane (textarea );
Contentpane. Add (PANE, borderlayout. center );

// Create buffer for output
Stringwriter buffer = new stringwriter ();
Printwriter out = new printwriter (buffer );

// Create initial list to sort
List list = new arraylist (arrays. aslist (words ));
Out. println ("original list :");
Out. println (list );
Out. println ();

// Perform default sort
Collections. Sort (list );
Out. println ("Default sorting :");
Out. println (list );
Out. println ();

// Reset list
List = new arraylist (arrays. aslist (words ));

// Perform case insensitive sort
Comparator comp = new caseinsensitivecomparator ();
Collections. Sort (list, comp );
Out. println ("Case Insensitive sorting :");
Out. println (list );
Out. println ();

// Reset list
List = new arraylist (arrays. aslist (words ));

// Perform collation sort
Comp = new collatorcomparator ();
Collections. Sort (list, comp );
Out. println ("collator sorting :");
Out. println (list );
Out. println ();

// Fill text area and display
Textarea. settext (buffer. tostring ());
Frame. Pack ();
Frame. Show ();
}
}

If your primary problem is sequential access, the list may not be your preferred data structure. As long as your set is not repeated, you can save your elements (provide or do not provide comparator) in the treeset ). In this way, elements are always sorted.


Author's blog:Http://blog.csdn.net/chensheng913/

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.