原文鏈接:https://blog.csdn.net/qq_35788725/article/details/82259013
Collections.sort可對集合進行排序
根據List里面某個字段進行出重篩選,此文是使用compareTo 比較器。請看代碼:
public static void main(String[] args) {
//
List<one> oneList = new ArrayList<one>();
oneList.add(new one(1, "11111"));
oneList.add(new one(2, "22222"));
oneList.add(new one(4, "33333"));
oneList.add(new one(3, "11111"));
oneList.add(new one(5, "44444"));
oneList.add(new one(6, "44444"));
oneList.add(new one(7, "55555"));
//=======比較器===========================================
Set<one> treeSet = new TreeSet<one>(new Comparator<one>(){
@Override
public int compare(one o1, one o2) {
//升序
int compareTo = o1.getName().compareTo(o2.getName());
//降序
//int compareTo = o2.getName().compareTo(o1.getName());
return compareTo;
}
});
treeSet.addAll(oneList);
//放入新的list 或者把當前的list進行close
List<one> arrayList = new ArrayList<>(treeSet);
for (one one : arrayList) {
System.out.println(one.getName());
}
}
}
//實體
class one{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public one(int id, String name) {
super();
this.id = id;
this.name = name;
}
public one() {
super();
// TODO Auto-generated constructor stub
}
}
運行結果:
==========處理前========
11111
22222
33333
11111
44444
44444
55555
==========處理后========
11111
22222
33333
44444
55555
以上就是根據list的某個字段用compareto來去重。
以下是關於compareTo()的淺解:
compareTo(): 方法用於將 Number 對象與方法的參數進行比較。可用於比較 Byte, Long, Integer等。
該方法用於兩個相同數據類型的比較,兩個不同類型的數據不能用此方法來比較(runoob.com解釋)。
compareTo():
如果指定的數與參數相等返回0。
如果指定的數小於參數返回 -1。
如果指定的數大於參數返回 1。
示例:
public static void main(String[] args) {
Integer a = 99;
System.out.println(a.compareTo(88));
System.out.println(a.compareTo(100));
System.out.println(a.compareTo(99));
}
運行結果:
1
-1
0