Java中使用Collections.sort()方法對數字和字符串泛型的LIst進行排序


在List的排序中常用的是Collections.sort()方法,可以對String類型和Integer類型泛型的List集合進行排序。

首先演示sort()方法對Integer類型泛型的List排序

 1 /*
 2      * 通過Collections.sort()方法,對Integer類型的泛型List進行排序
 3      */
 4     public void testSort1(){
 5         List<Integer> integerList = new ArrayList<Integer>();
 6         //插入100以內的十個隨機數
 7         Random ran = new Random();
 8         Integer k;
 9         for(int i=0;i<10;i++){
10             do{
11             k = ran.nextInt(100);
12             }while(integerList.contains(k));
13             integerList.add(k);
14             System.out.println("成功添加整數"+k);
15         }
16         
17         System.out.println("\n-------排序前------------\n");
18     
19         for (Integer integer : integerList) {
20             System.out.print("元素:"+integer);
21         }
22         Collections.sort(integerList);
23         System.out.println("\n-------排序后------------\n");
24         for (Integer integer : integerList) {
25             System.out.print("元素:"+integer);
26         }
27     }

 

打印輸出的結果為:

成功添加整數4
成功添加整數56
成功添加整數85
成功添加整數8
成功添加整數14
成功添加整數89
成功添加整數96
成功添加整數0
成功添加整數90
成功添加整數63

-------排序前------------

元素:4元素:56元素:85元素:8元素:14元素:89元素:96元素:0元素:90元素:63
-------排序后------------

元素:0元素:4元素:8元素:14元素:56元素:63元素:85元素:89元素:90元素:96

 

對String類型泛型的List進行排序

 1 /*
 2      * 對String泛型的List進行排序
 3      */
 4     public void testSort2(){
 5         List<String> stringList = new ArrayList<String>();
 6         stringList.add("imooc");
 7         stringList.add("lenovo");
 8         stringList.add("google");
 9         System.out.println("\n-------排序前------------\n");
10         for (String str : stringList) {
11             System.out.print("元素:"+str);
12         }
13         Collections.sort(stringList);
14         System.out.println("\n-------排序后------------\n");
15         for (String str : stringList) {
16             System.out.print("元素:"+str);
17         }
18     }

 

打印輸出的結果為:

-------排序前------------

元素:imooc元素:lenovo元素:google
-------排序后------------

元素:google元素:imooc元素:lenovo

 

使用sort()方法對String類型泛型的List進行排序時,首先是判斷首字母的順序,首字母相同時再判斷其后面的字母順序,具體的排序規則為:

1、數字0-9;

2、大寫字母A-Z;

3、小寫字母a-z

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM