TreeSet和HashSet的区别在于, TreeSet可以进行排序, 默认使用字典顺序排序, 也可以进行自定义排序
1, 自然排序
2, 比较器排序
自然排序:
1, 需要被排序的类实现Comparable接口
2, 重写其中的 comparato
/**
- Student类
- @author wenbronk
*/
public class Student implements Comparable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student s) {
//return -1; //-1表示放在红黑树的左边,即逆序输出
//return 1; //1表示放在红黑树的右边,即顺序输出
//return o; //表示元素相同,仅存放第一个元素
this.age.compareTo(s.age)return num2;
}
}
自定义比较器排序;
这种方法需要一个新的类实现Comparator接口
重写其中的Compare 方法
TreeSet<String> wifiSet = new TreeSet<String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
JSONObject obj1 = JSON.parseObject(o1);
JSONObject obj2 = JSON.parseObject(o2);
return obj1.getDouble("distance").compareTo(obj2.getDouble("distance"));
}
});
然后, 改成函数式编程可以写成:
Set<JSONObject> treeSet = new TreeSet<>((first, second) -> {
JSONObject base1 = first.getJSONObject("base");
String[] loc1 = base1.getString("location").split(", * ");
JSONObject base2 = second.getJSONObject("base");
String[] loc2 = base2.getString("location").split(", * ");
Double d1 = GeoUtils.getDistance(new Point(Double.valueOf(loc1[1]), Double.valueOf(loc1[0])),
new Point(lat, lng));
Double d2 = GeoUtils.getDistance(new Point(Double.valueOf(loc2[1]), Double.valueOf(loc2[0])),
new Point(lat, lng));
return d1.compareTo(d2);
});
然后正常往set中添加元素, 既可以实现自定义排序了