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

 

posted @ 2016-07-19 10:58  Web1024  阅读(8298)  评论(0编辑  收藏  举报