标签:package method lis generated span obj string ext col
工作中,我们经常会遇到需要进行各种排序的需求。现在就对于在工作中遇到的“根据名称进行排序”进行归纳总结。
1 package compare; 2 3 /** 4 * @Todo 要排序的实体类 5 * @author Wu Yuwei 6 * @date 2019年2月25日下午10:47:02 7 */ 8 public class CompareDao implements Comparable<CompareDao>{ 9 10 private String name; 11 private int age; 12 13 public CompareDao(String name, int age) { 14 super(); 15 this.name = name; 16 this.age = age; 17 } 18 19 public String getName() { 20 return name; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public int getAge() { 28 return age; 29 } 30 31 public void setAge(int age) { 32 this.age = age; 33 } 34 35 @Override 36 public int compareTo(CompareDao name) { 37 // TODO Auto-generated method stub 38 return this.getName().compareTo(name.getName()); 39 } 40 41 @Override 42 public String toString() { 43 return "CompareDao [name=" + name + ", age=" + age + "]"; 44 } 45 46 }
1 package compare; 2 3 import java.text.Collator; 4 import java.util.ArrayList; 5 import java.util.Collections; 6 import java.util.Comparator; 7 import java.util.List; 8 9 import org.junit.Test; 10 11 public class Compare { 12 13 /** 14 * 根据中文名称排序 15 */ 16 @Test 17 public void test01(){ 18 List<CompareDao> list = init(); 19 Collections.sort(list, new Comparator<CompareDao>() { 20 21 @Override 22 public int compare(CompareDao o1, CompareDao o2) { 23 Comparator<Object> compare = Collator.getInstance(java.util.Locale.CHINA); 24 return compare.compare(o1.getName(), o2.getName()); 25 } 26 }); 27 System.out.println(list); 28 29 } 30 31 /** 32 * 初始化 33 */ 34 public static List<CompareDao> init() { 35 CompareDao dao1 = new CompareDao("陈好", 20); 36 CompareDao dao2 = new CompareDao("陈赫", 30); 37 CompareDao dao3 = new CompareDao("陈家", 20); 38 CompareDao dao4 = new CompareDao("程咬金", 20); 39 CompareDao dao5 = new CompareDao("陈真", 80); 40 CompareDao dao6 = new CompareDao("蔡明", 60); 41 CompareDao dao7 = new CompareDao("蔡国庆", 65); 42 CompareDao dao8 = new CompareDao("方世玉", 80); 43 CompareDao dao9 = new CompareDao("马云", 50); 44 CompareDao dao10 = new CompareDao("张国荣", 60); 45 CompareDao dao11 = new CompareDao("张学友", 55); 46 47 48 List<CompareDao> list = new ArrayList<>(); 49 list.add(dao1); 50 list.add(dao2); 51 list.add(dao3); 52 list.add(dao4); 53 list.add(dao5); 54 list.add(dao6); 55 list.add(dao7); 56 list.add(dao8); 57 list.add(dao9); 58 list.add(dao10); 59 list.add(dao11); 60 return list; 61 } 62 }
排序结果:
[CompareDao [name=蔡国庆, age=65], CompareDao [name=蔡明, age=60], CompareDao [name=陈好, age=20], CompareDao [name=陈赫, age=30], CompareDao [name=陈家, age=20], CompareDao [name=陈真, age=80], CompareDao [name=程咬金, age=20], CompareDao [name=方世玉, age=80], CompareDao [name=马云, age=50], CompareDao [name=张国荣, age=60], CompareDao [name=张学友, age=55]]
思路总结:
本屌第一次写博客,哈哈简陋极了!!!
标签:package method lis generated span obj string ext col
原文地址:https://www.cnblogs.com/romeblogs/p/10434503.html