zoukankan      html  css  js  c++  java
  • JAVA对ArrayList排序

    ava如何对ArrayList中对象按照该对象某属性排序 

     

    增加排序功能,打印时:输出学生对象的时候,需要先按照年龄排序,如果年龄相同,则按照姓名排序,如果姓名也相同,则按照学号排序。
    

     

    Java代码  收藏代码
    1. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->import java.util.ArrayList;  
    2. import java.util.Collections;  
    3. import java.util.Comparator;  
    4.   
    5. public class ComparableTest {  
    6.  public static void main(String[] args) {  
    7.   Comparator<Student> comparator = new Comparator<Student>(){  
    8.    public int compare(Student s1, Student s2) {  
    9.     //先排年龄  
    10.     if(s1.age!=s2.age){  
    11.      return s1.age-s2.age;  
    12.     }  
    13.     else{  
    14.      //年龄相同则按姓名排序  
    15.      if(!s1.name.equals(s2.name)){  
    16.       return s1.name.compareTo(s2.name);  
    17.      }  
    18.      else{  
    19.       //姓名也相同则按学号排序  
    20.       return s1.id-s2.id;  
    21.      }  
    22.     }  
    23.    }  
    24.   };  
    25.   Student stu1 = new Student (1,"zhangsan","male",28,"cs");  
    26.   Student stu2 = new Student (2,"lisi","female",19,"cs");  
    27.   Student stu3 = new Student (3,"wangwu","male",22,"cs");  
    28.   Student stu4 = new Student (4,"zhaoliu","female",17,"cs");  
    29.   Student stu5 = new Student (5,"jiaoming","male",22,"cs");  
    30.   
    31.   ArrayList<Student> List = new ArrayList<Student>();  
    32.   List.add(stu1);  
    33.   List.add(stu2);  
    34.   List.add(stu3);  
    35.   List.add(stu4);  
    36.   List.add(stu5);   
    37.   //这里就会自动根据规则进行排序  
    38.   Collections.sort(List,comparator);  
    39.   display(List);  
    40.  }  
    41.    
    42.  static void display(ArrayList<Student> lst){  
    43.   for(Student s:lst)  
    44.    System.out.println(s);  
    45.  }  
    46. }  
    47.   
    48. class Student{  
    49.  int age;  
    50.  int id;  
    51.  String gender;  
    52.  String name;  
    53.  String cs;  
    54.  Student(int id,String name,String gender,int age,String cs){  
    55.   this.age=age;  
    56.   this.name=name;  
    57.   this.gender=gender;  
    58.   this.id=id;  
    59.   this.cs=cs;  
    60.  }  
    61.  public String toString(){  
    62.   return id+"  "+name+"  "+gender+"  "+age+"  "+cs;  
    63.  }  
    64. }  

     

    以一个point点类做例子:

    Java代码  收藏代码
    1. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->import java.util.*;     
    2.     
    3. public class Test {     
    4.     
    5. public static void main(String[] args){     
    6.   List<Point> points=new ArrayList<Point>();     
    7.        
    8.   Point point1=new Point();     
    9.   point1.setX(1324);     
    10.   point1.setY(345);     
    11.   point1.setZ(436);     
    12.   points.add(point1);     
    13.        
    14.   Point point2=new Point();     
    15.   point2.setX(23);     
    16.   point2.setY(8941.656);     
    17.   point2.setZ(431412);     
    18.   points.add(point2);     
    19.        
    20.   Point point3=new Point();     
    21.   point3.setX(786584);     
    22.   point3.setY(23452);     
    23.   point3.setZ(43563);     
    24.   points.add(point3);     
    25.        
    26.   //根据X排序     
    27.   Collections.sort(points,new SortByX());     
    28.        
    29.   for(Point p:points){     
    30.    System.out.print(p.getX()+" "+p.getY()+" "+p.getZ());     
    31.    System.out.println();     
    32.   }     
    33.        
    34.   //根据Y排序     
    35. //  Collections.sort(points,new SortByY());     
    36. //       
    37. //  for(Point p:points){     
    38. //   System.out.print(p.getX()+" "+p.getY()+" "+p.getZ());     
    39. //   System.out.println();     
    40. //  }     
    41. //       
    42. //  //根据Z排序     
    43. //  Collections.sort(points,new SortByZ());     
    44. //       
    45. //  for(Point p:points){     
    46. //   System.out.print(p.getX()+" "+p.getY()+" "+p.getZ());     
    47. //   System.out.println();     
    48. //  }     
    49. }     
    50.     
    51. }     
    52.     
    53. class Point{     
    54. private double x;     
    55. private double y;     
    56. private double z;     
    57. public double getX() {     
    58.   return x;     
    59. }     
    60. public void setX(double x) {     
    61.   this.x = x;     
    62. }     
    63. public double getY() {     
    64.   return y;     
    65. }     
    66. public void setY(double y) {     
    67.   this.y = y;     
    68. }     
    69. public double getZ() {     
    70.   return z;     
    71. }     
    72. public void setZ(double z) {     
    73.   this.z = z;     
    74. }     
    75. public Point(){}     
    76. }     
    77.     
    78. //根据X排序     
    79. class SortByX implements Comparator{     
    80. public int compare(Object obj1,Object obj2){     
    81.   Point point1=(Point)obj1;     
    82.   Point point2=(Point)obj2;     
    83.   if(point1.getX()>point2.getX())     
    84.    return 1;     
    85.   else    
    86.    return 0;     
    87. }     
    88. }     
    89. //根据Y排序     
    90. class SortByY implements Comparator{     
    91. public int compare(Object obj1,Object obj2){     
    92.   Point point1=(Point)obj1;     
    93.   Point point2=(Point)obj2;     
    94.   if(point1.getY()>point2.getY())     
    95.    return 1;     
    96.   else    
    97.    return 0;     
    98. }     
    99. }     
    100. //根据Z排序     
    101. class SortByZ implements Comparator{     
    102. public int compare(Object obj1,Object obj2){     
    103.   Point point1=(Point)obj1;     
    104.   Point point2=(Point)obj2;     
    105.   if(point1.getZ()>point2.getZ())     
    106.    return 1;     
    107.   else    
    108.    return 0;     
    109. }     
    110. }  

     

    Java代码  收藏代码
    1. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->//一个POJO例子  
    2.   
    3. class User {  
    4.  String name;  
    5.  String age;  
    6.    
    7.  public User(String name,String age){  
    8.   this.name=name;  
    9.   this.age=age;  
    10.  }  
    11.  public String getAge() {  
    12.   return age;  
    13.  }  
    14.  public void setAge(String age) {  
    15.   this.age = age;  
    16.  }  
    17.  public String getName() {  
    18.   return name;  
    19.  }  
    20.  public void setName(String name) {  
    21.   this.name = name;  
    22.  }   
    23. }  
    24.   
    25.   
    26. //具体的比较类,实现Comparator接口  
    27.   
    28. import java.util.Comparator;  
    29. import java.util.List;  
    30. import java.util.ArrayList;  
    31. import java.util.Collections;  
    32.   
    33. public class ComparatorUser implements Comparator{  
    34.   
    35.  public int compare(Object arg0, Object arg1) {  
    36.   User user0=(User)arg0;  
    37.   User user1=(User)arg1;  
    38.   
    39.    //首先比较年龄,如果年龄相同,则比较名字  
    40.   
    41.   int flag=user0.getAge().compareTo(user1.getAge());  
    42.   if(flag==0){  
    43.    return user0.getName().compareTo(user1.getName());  
    44.   }else{  
    45.    return flag;  
    46.   }    
    47.  }  
    48.    
    49. }  
    50.   
    51.   
    52.   
    53.   
    54. //测试类  
    55. public class SortTest {  
    56.   
    57.    
    58.  public static void main(String[] args){  
    59.   List userlist=new ArrayList();  
    60.   userlist.add(new User("dd","4"));  
    61.   userlist.add(new User("aa","1"));  
    62.   userlist.add(new User("ee","5"));  
    63.   userlist.add(new User("bb","2"));    
    64.   userlist.add(new User("ff","5"));  
    65.   userlist.add(new User("cc","3"));  
    66.   userlist.add(new User("gg","6"));  
    67.     
    68.   ComparatorUser comparator=new ComparatorUser();  
    69.   Collections.sort(userlist, comparator);  
    70.      
    71.   for (int i=0;i<userlist.size();i++){  
    72.    User user_temp=(User)userlist.get(i);  
    73.       System.out.println(user_temp.getAge()+","+user_temp.getName());   
    74.   }  
    75.     
    76.  }  
    77. }  
    78.   
    79.  //首先年龄排序,如果年龄相同,则按名字排序  

     

    结果:
       1, aa
       2, bb
       3, cc
       4, dd
       5, ee                    //注意:同样是5岁的人,则比较名字(ee,ff),然后排序
       5, ff
       6, gg

     

     http://zhidao.baidu.com/question/135304880.html?push=ql

    最后这个没有用java的Comparable接口,自己写的排序函数。

     

    要用JAVA写个东西读取TXT中的数据 且要计算出平均值和总值 最后还要按总值排序。 
     TXT的文件如下:
    
    学号 姓名   语文 数学 英语 平均值 总值  排序
    1   李守东   83  73  75
    2   徐贤坤   58  58  87
    3   钱云宋   41  86  90
    4   陈平     83  43  65
    5   金荣权   93  88  63
    6   陈如棉   99  93  43
    7   章可可   98  62  72
    8   陈伟奔   87  43  76
    9   张如祥   69  58  78
    10  丁尚游   80  56  57
    11  林宏旦   91  90  76
    12  曾上腾   100 96  54
    13  谢作品   82  100 55
    14  温从卫   73  46  101
    15  李明察   81  41  75
    16  彭鸿威   46  46  89
    17  翁文秀   57  43  58
    18  陈家伟   63  58  98
    19  温正考   100 64  57
    20  周文湘   50  50  79
    21  吴杰     65  65  83
    22  赖登城   60  79  53
    23  聂树露   51  76  45
    24  张雅琴   68  95  56
    25  曾瑞约   88  63  58
    26  王志强   96  79  78
    27  徐贤所   66  46  74
    28  陈祥枭   82  96  91
    29  温婷婷   41  73  96
    30  应孔余   66  81  71
    31  宋成取   71  68  62
    32  黄益省   65  56  43
    33  陈思文   55  100 44
    34  上官福新 64  62  70
    35  钟国横   49  69  56
    36  林型涨   78  73  50 

     代码:

    Java代码  收藏代码
      1. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->import java.io.BufferedReader;  
      2. import java.io.File;  
      3. import java.io.FileNotFoundException;  
      4. import java.io.FileReader;  
      5. import java.io.IOException;  
      6. import java.io.PrintWriter;  
      7. import java.util.ArrayList;  
      8. import java.util.HashMap;  
      9. import java.util.List;  
      10. import java.util.Map;  
      11.   
      12. public class Testa   
      13. {  
      14.  public static void main(String[] args)   
      15.  {  
      16.   //传入参数为文件目录  
      17.   test("d:/a.txt");  
      18.  }  
      19.    
      20.  public static void test(String filePath){  
      21.   BufferedReader br = null;  
      22.   try {  
      23.    br = new BufferedReader(new FileReader(filePath));  
      24.   } catch (FileNotFoundException e) {  
      25.    e.printStackTrace();  
      26.    return;  
      27.   }  
      28.     
      29.   String []columnName = {"Id""Name""Languages""Math""English"}; //列名  
      30.   int []courseIndexs = {234};          //课程对应的列  
      31.   int i,j,index;  
      32.   String line;  
      33.   List<Map<String, Object>> students = new ArrayList<Map<String, Object>>();  
      34.   //记录Id和总值,用于排序  
      35.   List<Map<String, Object>> sortList = new ArrayList<Map<String, Object>>();  
      36.   try {  
      37.    br.readLine(); //去掉第一行  
      38.    while((line = br.readLine()) != null){  
      39.     index = 0;  
      40.     String []se = line.split(" ");  
      41.     Map<String, Object> student = new HashMap<String, Object>();  
      42.     for(i = 0; i < se.length; i++){  
      43.      if("".equals(se[i])){  
      44.       continue;  
      45.      }  
      46.      if(index >= columnName.length){  
      47.       continue;  
      48.      }  
      49.      student.put(columnName[index], se[i]);  
      50.      index++;  
      51.     }  
      52.     //计算平均值,总值  
      53.     double total = 0;  
      54.     for(j = 0; j < courseIndexs.length; j++){  
      55.      total += Double.parseDouble((String) student.get(columnName[courseIndexs[j]]));  
      56.     }  
      57.     double average = total / courseIndexs.length;  
      58.     //只取一位小数  
      59.     average = Math.round(average * 10)/10;  
      60.     student.put("Total", total);  
      61.     student.put("Average", average);  
      62.       
      63.     Map<String, Object> sort = new HashMap<String, Object>();  
      64.     sort.put("Id", student.get("Id"));  
      65.     sort.put("Total", student.get("Total"));  
      66.     sortList.add(sort);  
      67.       
      68.     students.add(student);  
      69.    }  
      70.    br.close();  
      71.      
      72.    //选择排序  
      73.    for(i = 0; i < sortList.size(); i++){  
      74.     for(j = i + 1; j < sortList.size(); j++){  
      75.      if((Double)sortList.get(i).get("Total") < (Double)sortList.get(j).get("Total")){  
      76.       Map<String, Object> temp = sortList.get(i);  
      77.       sortList.set(i, sortList.get(j));  
      78.       sortList.set(j, temp);  
      79.      }  
      80.     }  
      81.    }  
      82.    Map<Object, Integer> sortedId = new HashMap<Object, Integer>();  
      83.    for(i = 0; i < sortList.size(); i++){  
      84.     sortedId.put(sortList.get(i).get("Id"), i+1);  
      85.    }  
      86.      
      87.    //设定序号  
      88.    for(j = 0; j < students.size(); j++){  
      89.     students.get(j).put("Order", sortedId.get(students.get(j).get("Id")));  
      90.    }  
      91.      
      92.    //输出(写到原文件)  
      93.    //PrintWriter pw = new PrintWriter(new File(filePath));  
      94.    //输出(写到其他文件)  
      95.    PrintWriter pw = new PrintWriter(new File("D:/b.txt"));  
      96.      
      97.    pw.println("Id Name Lan Math English Average Total Sort");  
      98.    int cIndex;  
      99.    for(i = 0; i < students.size(); i++){  
      100.     Map<String, Object> st = students.get(i);  
      101.     cIndex = 0;  
      102.     pw.println(st.get(columnName[cIndex++]) + " " + st.get(columnName[cIndex++])  
      103.       + " " + st.get(columnName[cIndex++])+ " " + st.get(columnName[cIndex++])  
      104.       + " " + st.get(columnName[cIndex++])  
      105.       + " " + st.get("Total")  
      106.       + " " + st.get("Average")  
      107.       + " " + st.get("Order"));  
      108.    }  
      109.    pw.flush();  
      110.    pw.close();  
      111.   } catch (IOException e) {  
      112.    e.printStackTrace();  
      113.   }  
      114.  }  

  • 相关阅读:
    Java RMI 使用例子
    Hessian 使用例子
    Spring 使用javaconfig配置aop
    Spring 使用xml配置aop
    Spring Junit集成测试
    Spring 使用javaconfig配置
    Spring @Autowired注解用在集合上面,可以保持接口的所有实现类
    在linux上搭建nexus私服(CentOS7)
    PostgresSQL使用Copy命令能大大提高数据导入速度
    PHP curl get post请求
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/3465345.html
Copyright © 2011-2022 走看看