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

增加排序功能,打印时:输出学生对象的时候,需要先按照年龄排序,如果年龄相同,则按照姓名排序,如果姓名也相同,则按照学号排序。
  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. public class ComparableTest {
  5. public static void main(String[] args) {
  6. Comparator<Student> comparator = new Comparator<Student>(){
  7. public int compare(Student s1, Student s2) {
  8. //先排年龄
  9. if(s1.age!=s2.age){
  10. return s1.age-s2.age;
  11. }
  12. else{
  13. //年龄相同则按姓名排序
  14. if(!s1.name.equals(s2.name)){
  15. return s1.name.compareTo(s2.name);
  16. }
  17. else{
  18. //姓名也相同则按学号排序
  19. return s1.id-s2.id;
  20. }
  21. }
  22. }
  23. };
  24. Student stu1 = new Student (1,"zhangsan","male",28,"cs");
  25. Student stu2 = new Student (2,"lisi","female",19,"cs");
  26. Student stu3 = new Student (3,"wangwu","male",22,"cs");
  27. Student stu4 = new Student (4,"zhaoliu","female",17,"cs");
  28. Student stu5 = new Student (5,"jiaoming","male",22,"cs");
  29. ArrayList<Student> List = new ArrayList<Student>();
  30. List.add(stu1);
  31. List.add(stu2);
  32. List.add(stu3);
  33. List.add(stu4);
  34. List.add(stu5);
  35. //这里就会自动根据规则进行排序
  36. Collections.sort(List,comparator);
  37. display(List);
  38. }
  39. static void display(ArrayList<Student> lst){
  40. for(Student s:lst)
  41. System.out.println(s);
  42. }
  43. }
  44. class Student{
  45. int age;
  46. int id;
  47. String gender;
  48. String name;
  49. String cs;
  50. Student(int id,String name,String gender,int age,String cs){
  51. this.age=age;
  52. this.name=name;
  53. this.gender=gender;
  54. this.id=id;
  55. this.cs=cs;
  56. }
  57. public String toString(){
  58. return id+"  "+name+"  "+gender+"  "+age+"  "+cs;
  59. }
  60. }

以一个point点类做例子:

  1. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->import java.util.*;
  2. public class Test {
  3. public static void main(String[] args){
  4. List<Point> points=new ArrayList<Point>();
  5. Point point1=new Point();
  6. point1.setX(1324);
  7. point1.setY(345);
  8. point1.setZ(436);
  9. points.add(point1);
  10. Point point2=new Point();
  11. point2.setX(23);
  12. point2.setY(8941.656);
  13. point2.setZ(431412);
  14. points.add(point2);
  15. Point point3=new Point();
  16. point3.setX(786584);
  17. point3.setY(23452);
  18. point3.setZ(43563);
  19. points.add(point3);
  20. //根据X排序
  21. Collections.sort(points,new SortByX());
  22. for(Point p:points){
  23. System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
  24. System.out.println();
  25. }
  26. //根据Y排序
  27. //  Collections.sort(points,new SortByY());
  28. //
  29. //  for(Point p:points){
  30. //   System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
  31. //   System.out.println();
  32. //  }
  33. //
  34. //  //根据Z排序
  35. //  Collections.sort(points,new SortByZ());
  36. //
  37. //  for(Point p:points){
  38. //   System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
  39. //   System.out.println();
  40. //  }
  41. }
  42. }
  43. class Point{
  44. private double x;
  45. private double y;
  46. private double z;
  47. public double getX() {
  48. return x;
  49. }
  50. public void setX(double x) {
  51. this.x = x;
  52. }
  53. public double getY() {
  54. return y;
  55. }
  56. public void setY(double y) {
  57. this.y = y;
  58. }
  59. public double getZ() {
  60. return z;
  61. }
  62. public void setZ(double z) {
  63. this.z = z;
  64. }
  65. public Point(){}
  66. }
  67. //根据X排序
  68. class SortByX implements Comparator{
  69. public int compare(Object obj1,Object obj2){
  70. Point point1=(Point)obj1;
  71. Point point2=(Point)obj2;
  72. if(point1.getX()>point2.getX())
  73. return 1;
  74. else
  75. return 0;
  76. }
  77. }
  78. //根据Y排序
  79. class SortByY implements Comparator{
  80. public int compare(Object obj1,Object obj2){
  81. Point point1=(Point)obj1;
  82. Point point2=(Point)obj2;
  83. if(point1.getY()>point2.getY())
  84. return 1;
  85. else
  86. return 0;
  87. }
  88. }
  89. //根据Z排序
  90. class SortByZ implements Comparator{
  91. public int compare(Object obj1,Object obj2){
  92. Point point1=(Point)obj1;
  93. Point point2=(Point)obj2;
  94. if(point1.getZ()>point2.getZ())
  95. return 1;
  96. else
  97. return 0;
  98. }
  99. }
  1. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->//一个POJO例子
  2. class User {
  3. String name;
  4. String age;
  5. public User(String name,String age){
  6. this.name=name;
  7. this.age=age;
  8. }
  9. public String getAge() {
  10. return age;
  11. }
  12. public void setAge(String age) {
  13. this.age = age;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. }
  22. //具体的比较类,实现Comparator接口
  23. import java.util.Comparator;
  24. import java.util.List;
  25. import java.util.ArrayList;
  26. import java.util.Collections;
  27. public class ComparatorUser implements Comparator{
  28. public int compare(Object arg0, Object arg1) {
  29. User user0=(User)arg0;
  30. User user1=(User)arg1;
  31. //首先比较年龄,如果年龄相同,则比较名字
  32. int flag=user0.getAge().compareTo(user1.getAge());
  33. if(flag==0){
  34. return user0.getName().compareTo(user1.getName());
  35. }else{
  36. return flag;
  37. }
  38. }
  39. }
  40. //测试类
  41. public class SortTest {
  42. public static void main(String[] args){
  43. List userlist=new ArrayList();
  44. userlist.add(new User("dd","4"));
  45. userlist.add(new User("aa","1"));
  46. userlist.add(new User("ee","5"));
  47. userlist.add(new User("bb","2"));
  48. userlist.add(new User("ff","5"));
  49. userlist.add(new User("cc","3"));
  50. userlist.add(new User("gg","6"));
  51. ComparatorUser comparator=new ComparatorUser();
  52. Collections.sort(userlist, comparator);
  53. for (int i=0;i<userlist.size();i++){
  54. User user_temp=(User)userlist.get(i);
  55. System.out.println(user_temp.getAge()+","+user_temp.getName());
  56. }
  57. }
  58. }
  59. //首先年龄排序,如果年龄相同,则按名字排序

结果:
   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

代码:

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

最新文章

  1. Maven 打包涉及证书文件问题
  2. 个性化EDM数据营销的三大提醒
  3. JSP业务逻辑层
  4. centos6.5安装配置fastdfs+nginx实现分布式图片服务器
  5. SDcard进行文件的读取
  6. storm - 基础概念整理
  7. 问题-Delphi 中使用TStringList后,报out of memory 的解决方法
  8. 解决MySQL服务启动时报1067错误
  9. JVM基础和调优(四)
  10. Paragraph 对象&#39;代表所选内容、范围或文档中的一个段落。Paragraph 对象是 Paragraphs 集合的一个成员。Paragraphs 集合包含所选内容、范围或文档中的所有段落。
  11. XSS研究2-来自内部的XSS攻击的防范
  12. 关于spring的aop拦截的问题 protected方法代理问题
  13. 使用springcloud zuul构建接口网关
  14. Linux的vim编辑器中的翻页命令
  15. java利用反射动态加载方法
  16. CSS基础一
  17. Android : 跟我学Binder --- (3) C程序示例
  18. RQNOJ 1 明明的随机数
  19. Lucene 4.X 全套教程
  20. ActivityThread

热门文章

  1. Cisco无线控制器配置
  2. windows 下OPENSSL 生成秘钥和公钥的方法
  3. ElasticSearch 获取es集群信息
  4. 解决从github上下载代码仓库慢的问题
  5. solr的使用
  6. 【leetcode算法-简单】20. 有效的括号
  7. [转帖]ubuntu 修改 apt源的方法
  8. Python+request超时和重试
  9. 使用pycharm开发web——django2.1.5(四)视图和模板相关
  10. Linux Centos下软件的安装与卸载方法