Java实现对List中的对象按某个字段进行排序


1 public class Logs implements Serializable, Comparable { 2
3 private String id; 4 private String username; 5 private String contents; 6 private String consequence; 7 private String ip; 8 private Long times; 9
10 @Override 11 public int compareTo(Logs o) { 12 return 0; 13 } 14
15 } 16 解析: Logs实体,要继承Comparable接口, 然后再实现一个public int compareTo(Logs o) 方法. 17 18 现在,我要对List 中的数据按 times 字段进行排序 19 20 21 @Test 22 public void testMath(){ 23 List list = new ArrayList(); 24 list.add(new Logs("1","chen", "djifand", "jdifa", "jdfid", 49L)); 25 list.add(new Logs("134","ce", "cae", "jdifa", "jdfid", 123L)); 26 list.add(new Logs("3","cet", "djifand", "jdifa", "jdfid", 99L)); 27 list.add(new Logs("4","egge", "djifand", "jdifa", "jdfid", 111L)); 28 list.add(new Logs("15","chen", "djifand", "jdifa", "jdfid", 59L)); 29 list.add(new Logs("6","chen2", "cae", "jdifa", "jdfid", 123L)); 30 list.add(new Logs("87","cet", "djifand", "jdifa", "jdfid", 213L)); 31 list.add(new Logs("8","egge", "djifand", "jdifa", "jdfid", 201L)); 32 list.add(new Logs("9","egge2", "djifand", "jdifa", "jdfid", 269L)); 33 list.add(new Logs("10","ce", "cae", "jdifa", "jdfid", 121L)); 34 list.add(new Logs("11","chen3", "djifand", "jdifa", "jdfid", 1123L)); 35 list.add(new Logs("5","cet2", "djifand", "jdifa", "jdfid", 12L)); 36
37 System.out.println("---- 排序前的输出 ----- "); 38 for (Logs logs : list) { 39 System.out.println("数据: "+logs); 40 } 41 System.out.println("---- 排序后的结果 ----- "); 42 List search = search(list); 43
44 for (Logs logs : search) { 45 System.out.println("-->"+logs); 46 } 47
48 } 49
50
51 // 方式1: 降序排列 52 public List search(List logsList){ 53 Collections.sort(logsList, new Comparator() { 54 @Override 55 public int compare(Logs o1, Logs o2) { 56 if ((o1.getTimes() > o2.getTimes())){ 57 return -1; 58 } 59 if (o1.getTimes() == o2.getTimes()){ 60 return 0; 61 } 62 return 1; 63 } 64 }); 65 return logsList; 66 } 67
68 // 方式2: 升序排列 69 public List search(List logsList){ 70 Collections.sort(logsList, new Comparator() { 71 @Override 72 public int compare(Logs o1, Logs o2) { 73 if ((o1.getTimes() > o2.getTimes())){ 74 return 1; 75 } 76 if (o1.getTimes() == o2.getTimes()){ 77 return 0; 78 } 79 return -1; 80 } 81 }); 82 return logsList; 83 } 84 // 方式3: 降序排列 85 public List search(List logsList){ 86 Collections.sort(logsList, new Comparator() { 87 @Override 88 public int compare(Logs o1, Logs o2) { 89 return -o1.getTimes().compareTo(o2.getTimes()); 90 } 91 }); 92 return logsList; 93 } 94
95 // 方式4: 升序排列 96 public List search(List logsList){ 97 Collections.sort(logsList, new Comparator() { 98 @Override 99 public int compare(Logs o1, Logs o2) { 100 return o1.getTimes().compareTo(o2.getTimes()); 101 } 102 }); 103 return logsList; 104 }


原文链接:https://www.cnblogs.com/masterpick/p/13267764.html


登录 - 评论

评论