字母排序,对象字段排序

字母排序

1         List list = new ArrayList();
2         list.add("fdd");
3         list.add("bbc");
4         list.add("bac");
5         list.add("abc");
6         Collections.sort(list);
7         Iterator iterator2 = list.iterator();
8         while (iterator2.hasNext()) System.out.println(iterator2.next());
1         for (int i = 0; i < list.size(); i++) {
2             System.out.println(list.get(i));
3         }

实体类中某个字段按字母排序,并“other"字段排最后:

 1         List<EntityA> l = new ArrayList<>();
 2         List<EntityA> l1 = new ArrayList<>();
 3         List<EntityA> l2 = new ArrayList<>();
 4         List<EntityA> l3 = new ArrayList<>();
 5         EntityA a1 = new EntityA();
 6         a1.setTa("51");
 7         a1.setTb("阿布");
 8         a1.setTc("other");
 9         a1.setTd("dkwoiweoiei");
10         EntityA a = new EntityA();
11         a.setTa("51");
12         a.setTb("阿布");
13         a.setTc("bbc");
14         a.setTd("dkwoiweoiei");
15         EntityA b = new EntityA();
16         b.setTa("12");
17         b.setTb("保持");
18         b.setTc("zba");
19         b.setTd("ddssw");
20         EntityA c = new EntityA();
21         c.setTa("26");
22         c.setTb("尺寸");
23         c.setTc("qwe");
24         c.setTd("adw");
25 
26         l.add(a);
27         l3.add(a1);
28         l1.add(c);
29         l2.add(b);
30         l.addAll(l1);
31         l2.addAll(l);
32         l3.addAll(l2);
33         Iterator<EntityA> iterator = l3.iterator();
34         EntityA otherTc = null;
35         while (iterator.hasNext()) {
36             EntityA entityA = iterator.next();
37             if (entityA.getTc().equals("other")) {
38                 otherTc = entityA;
39                 iterator.remove();
40                 break;
41             }
42         }
43         Collections.sort(l3);
44         l3.add(otherTc);
45         for (int i = 0; i < l3.size(); i++) {
46             System.out.println(l3.get(i).getTc());
47         }    
 1 package com.example.demo;
 2 
 3 import java.io.Serializable;
 4 
 5 public class EntityA implements Serializable,Comparable<EntityA> {
 6     //点击File–Setting–Editor–Inspections–Java–Serialization issues–勾选Serializable class without"serialVersionUID"即可,然后点击OK
 7     //第二步:选中实体类类名按住Alt+Enter,选择条目,即可生成serialVersionUID
 8     private static final long serialVersionUID = -5787205392747829684L;
 9     private String tc;
10     private String ta;
11     private String tb;
12     private String td;
13 
14     //get/set...
15 
16     @Override
17     public int compareTo(EntityA o) {
18         if(this.tc.compareTo(o.tc)<0)
19             return -1;
20         else if(this.tc.compareTo(o.tc)>0)
21             return 1;
22         else return 0;
23     }
24 }

 

posted @ 2020-12-08 18:58  Johnson718  阅读(250)  评论(0编辑  收藏  举报