Java集合中的排序方法

1.1.1. Comparable接口（了解）

TreeSet会调用元素的compareTo方法来比较元素的大小关系,然后将集合元素按照升序排列。

``````public interface Comparable {

public int compareTo(T o);

}
``````

• this > o：返回正整数 1 ，优先级较高

• this < o：返回负整数 -1 ，优先级较低

• this == o： 返回 0 ，此时认为两个对象为同一个对象。

``````class User implements java.lang.Comparable {

private String name;

private int age;

public User(String name, int age) {

this.name = name;

this.age = age;

}

//比较规则

public int compareTo(User o) {

if (this.age > o.age) {

return 1;

} else if (this.age < o.age) {

return -1;

}

return 0;

}

public String toString() {

return "User [name=" + name + ", age=" + age + "]";

}

}

public class ComparableDemo{

public static void main(String[] args) {

Set set = new TreeSet<>();

System.out.println(set);

}

}
``````

``````[User [name=allen, age=15], User [name=will, age=17], User [name=Lucy, age=22], User [name=stef, age=28]]
``````

image.png

image.png

image.png

image.png

image.png

1.1.2. Comparator接口（了解）

TreeSet除了默认支持自然排序外，还支持自定义排序，此时需要在构建TreeSet对象时传递java.util.Comparator接口的实现类对象，Comparator表示比较器，里面封装比较规则。

``````public interface Comparator {

int compare(T o1, T o2);

}
``````

``````class User {

private String name;

private int age;

public User(String name, int age) {

this.name = name;

this.age = age;

}

public int getAge() {

return age;

}

public String getName() {

return name;

}

public String toString() {

return "User [name=" + name + ", age=" + age + "]";

}

}

public class App {

public static void main(String[] args) {

Set set = new TreeSet<>(**new NameLengthComparator()**);

System.out.println(set);//

}

}

class NameLengthComparatorimplements java.util.Comparator {

public int compare(User o1, User o2) {

int ret = o1.getName().length() - o2.getName().length();

if (ret > 0) {

return 1;

} else if (ret < 0) {

return -1;

} else {

if (o1.getAge() > o2.getAge()) {

return 1;

} else if (o1.getAge() < o2.getAge()) {

return -1;

} else {

return 0;

}

}

}

}
``````

``````[User [name=Will, age=17], User [name=Allen, age=28], User [name=James, age=30], User [name=Bryant, age=22]]
``````