Mainly used: Collections. sort () method:
1. JavaBean -- Content. java:
- PackageCom. hmw. listsort;
- Public ClassContent {
- Private LongKey;
- PrivateString name;
- PublicContent (LongKey, String name ){
- This. Key = key;
- This. Name = name;
- }
- Public LongGetKey (){
- ReturnKey;
- }
- Public VoidSetKey (LongKey ){
- This. Key = key;
- }
- PublicString getName (){
- ReturnName;
- }
- Public VoidSetName (String name ){
- This. Name = name;
- }
- }
2. Comparison class -- ContentComparator. java:
- PackageCom. hmw. listsort;
- ImportJava. util. Comparator;
- Public ClassContentComparatorImplementsComparator <Content> {
- Public IntCompare (Content o1, Content o2 ){
- // Route null to the end
- If(O1 =Null){
- Return1;
- }
- If(O2 =Null|! (O2InstanceofContent )){
- Return-1;
- }
- LongKey1 = o1.getKey ();
- LongKey2 = o2.getKey ();
- ReturnKey1> key2? 1: key1 <key2? -1: 0;
- /*
- // If You Want To sort by name field, you only need to change the last three lines of code to the following line.
- Return o1.getName (). compareTo (o2.getName ());
- */
- }
- }
3. Test class -- CompareClient. java
- PackageCom. hmw. listsort;
- ImportJava. util. ArrayList;
- ImportJava. util. Collections;
- ImportJava. util. List;
- Public ClassCompareClient {
- Public Static VoidMain (String [] args ){
- List <content> List =NewArraylist <content> ();
- List. Add (Null);
- List. Add (NewContent (15000, "--- 15000 --"));
- List. Add (NewContent (10000, "--- 10000 ---"));
- List. Add (NewContent (20000, "--- 20000 ---"));
- List. Add (Null);
- List. Add (NewContent (25000, "--- 25000 ---"));
- List. add (NewContent (13000, "--- 13000 ---"));
- List. add (NewContent (15000, "--- 15000 ---"));
- List. add (NewContent (89000, "--- 89000 ---"));
- Collections. sort (list,NewContentComparator ());
- /*
- // Add this line of code in descending order.
- Collections. reverse (list );
- */
- For(Content content: list ){
- If(Content =Null){
- System. out. println ("null ");
- }Else{
- System. out. println ("content. getName ()/t" + content. getName ());
- }
- }
- }
- }
The output result is as follows:
Content. getName () --- 10000 ---
Content. getName () --- 13000 ---
Content. getName () --- 15000 --
Content. getName () --- 15000 ---
Content. getName () --- 20000 ---
Content. getName () --- 25000 ---
Content. getName () --- 89000 ---
Null
Null