zoukankan      html  css  js  c++  java
  • 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("
    -------排序前------------
    ");
    18     
    19         for (Integer integer : integerList) {
    20             System.out.print("元素:"+integer);
    21         }
    22         Collections.sort(integerList);
    23         System.out.println("
    -------排序后------------
    ");
    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("
    -------排序前------------
    ");
    10         for (String str : stringList) {
    11             System.out.print("元素:"+str);
    12         }
    13         Collections.sort(stringList);
    14         System.out.println("
    -------排序后------------
    ");
    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

  • 相关阅读:
    C# zip压缩文件的功能
    C#图解教程 第四章 第五章
    process.StandardOutput.ReadToEnd() 假死
    C# 图解教程 (类型 存储和变量)
    unity editor下选中GameObject粘贴复制pos信息
    Texture中指定具体颜色进行高亮显示
    unity 加载Assetbundle文件夹路径需要注意
    unity 文件移动注意 AB打包文件名注意小写
    linux总结应用之三 建立内核
    linux总结应用之二
  • 原文地址:https://www.cnblogs.com/jpwz/p/5683918.html
Copyright © 2011-2022 走看看