The List implementations defined in the Java Collection Framework include Vector, ArrayList and LinkedList. These collections provide indexed access to groups of objects. They provide support for adding and removing elements. However, they do not have built-in support for sorting elements.
You can use the sort() method in the java.util.Collections class to sort List elements. You can pass a List object to the method, or you can pass a List and a Comparator. If the elements in the list are all 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 don't want to use the default sort order, you can also pass a Comparator to the sort() method to sort. If the elements in the list are not all of the same type, you won't be 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 sort order is based on the character encoding, which is basically the ASCII/Unicode value of each character. If the strict restriction is to deal with English, the omitted sort order is usually sufficient, since it sorts A-Z first, then lowercase letters a-z. However, if you are dealing with non-English words, or you just want to use a different sort order, there is a second variation of Collections.sort(). For example, you want to sort strings in reverse order. In order to achieve this function, you can obtain a reverse order Comparator through reverseOrder() in the Collections class. Then, you pass the reverse Comparator to the sort() method. In other words, you do the following:
<p>List list = ...;<br>Comparator comp = Collections.reverseOrder();<br>Collections.sort(list, comp);</p> |
## If the list contains the items: Man, man, Woman , and woman, the sorted list would be Man, Woman, man, woman. Nothing complicated here. A very important point to note is that Collections.sort() performs in-place sorting. If you need to preserve the original order, you need to copy the original collection first and then sort it, like this:
<p>List list = ...;<br>List copyOfList = new ArrayList(list);<br>Collections.sort(copyOfList);</p>
|
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 do a case-insensitive sort? One way to do it is to implement Comparator like this:
##<p>public static class CaseInsensitiveComparator <br>implements Comparator {<br>public int compare(Object element1, <br>Object element2) {<br>String lower1 = <br>element1.toString().toLowerCase();<br>String lower2 = <br>element2.toString().toLowerCase();<br>return lower1.compareTo(lower2);<br>}<br>}</p>
|
You really don’t need to create this class manually . Instead, you can use the existing Comparator, CASE_INSENSIVTIVE_ORDER, which is defined in the String class.
There is a small problem with this implementation. 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 ordered differently, and this difference is determined by the order in which the two elements appear in the list.
What happens if the language is different? The java.text package provides the Collector and CollectionKey classes for language-sensitive sorting. Here is an example:
Note that if your text is in the local language instead of the default language, you need to pass a local language to the getInstance() method, like:
<p>public static class CollatorComparator <br>implements Comparator {<br>Collator collator = Collator.getInstance();<br>public int compare(Object element1, <br>Object element2) {<br>CollationKey key1 = collator.getCollationKey(<br>element1.toString());<br>CollationKey key2 = collator.getCollationKey(<br>element2.toString());<br>return key1.compareTo(key2);<br>}<br>}</p>
|
You are sorting the collection key, not the actual string. Not only does this provide fixed case-insensitive sorting, but it is sorting across languages. In other words, if you were sorting a mixture of Spanish and non-Spanish words, the word mañana (tomorrow) would be ranked before mantra. If you don't use Collector, mañana will come in behind mantra.
The following program performs different types of sorting on a list (default, case-sensitive, 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 {
<p>public static class CollatorComparator <br>implements Comparator {<br>Collator collator = Collator.getInstance();<br>public int compare(Object element1, <br>Object element2) {<br>CollationKey key1 = collator.getCollationKey(<br>element1.toString());<br>CollationKey key2 = collator.getCollationKey(<br>element2.toString());<br>return key1.compareTo(key2);<br>}<br>}</p>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.setDefaultCloseOperation(
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();
}
}
|
The above is the detailed content of How to implement Java list sorting function. For more information, please follow other related articles on the PHP Chinese website!