List中根據某個實體的屬性去重或者排序
阿新 • • 發佈:2019-01-04
引言
最近在在專案中對list的一些操作還是比較多的,其中有很多內建的工具類都很強大,但是這些都是對於基本型別的操作,但是我們在專案中操作最多的是我們自定義的物件,所以一些操作還是需要我們自己來封裝的,下面以排序和去重為例子。
一、去重
實體如下:
public class RobotCase implements Serializable { /** * 案件id */ private Long caseId; /** * 自增id */ private Long partnerId; /** * 甲方公司名稱 */ private String clientName; /** * 借款人姓名 */ private String borrowerName; /** * 借款人性別 1 男 0 女 */ private Byte borrowerSex; /** * 借款人電話 */ private String borrowerTel; 。。。。。。。。 }
根據RobotCase實體中的borrowerTel欄位進行去重,程式碼如下:
/** * @param * @return * @description 根據電話號碼去重 * @date 14:39 2018/6/19 * @author zhenghao */ private List<RobotCase> removeDuplicateCase(List<RobotCase> cases) { Set<RobotCase> set = new TreeSet<>(new Comparator<RobotCase>() { @Override public int compare(RobotCase o1, RobotCase o2) { //字串,則按照asicc碼升序排列 return o1.getBorrowerTel().compareTo(o2.getBorrowerTel()); } }); set.addAll(cases); return new ArrayList<>(set); }
二、排序
public class Student {
private int age;
private String name;
。。。
}
具體實現
/* * int compare(Student o1, Student o2) 返回一個基本型別的整型, * 返回負數表示:o1 小於o2, * 返回0 表示:o1和o2相等, * 返回正數表示:o1大於o2。 */ public List<Student>sort(List<Student>students){ Collections.sort(students, new Comparator<RobotCase>() { @Override public int compare(Student o1, Student o2) { //按照學生的年齡進行升序排列 ;<是降序 if(o1.getAge() > o2.getAge()){ return 1; } if(o1.getAge() == o2.getAge()){ return 0; } return -1; return o1.getAge()-o2.getAge();//升序 return o2.getAge()-o1.getAge();//降序 return o1.getName().compareTo(o2.getName()) ;// 按照姓名升序 return o2.getName().compareTo(o1.getName()) ;// 按照姓名降序 } }); return students; }