实例-阐释Compareable与Comparator
<pre><code>package com.example.demo.entity;
public class User implements Comparable<User> {
private Long id;
private String name;
public Long getId() {
return id;
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 按id 倒序
*
* @param o
* @return
*/
@Override
public int compareTo(User o) {
return (int) (o.id - this.id);
}
}
package com.example.demo;
import com.example.demo.entity.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class UserTest {
public static void main(String[] args) {
List<User> users=new ArrayList<>();
users.add(new User(5L,"金"));
users.add(new User(9L,"张"));
users.add(new User(11L,"李"));
users.add(new User(3L,"王"));
users.add(new User(1L,"虎"));
//实现了Compareable 接口的类 内部排序
Collections.sort(users);
for (User user : users) {
System.out.println(user.getName());
}
}
}
</code></pre>
<pre><code>package com.example.demo.entity;
public class Student {
private Long id;
private String name;
public Long getId() {
return id;
}
public Student(Long id) {
this.id = id;
}
public Student() {
}
public Student(Long id, String name) {
this.id = id;
this.name = name;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.demo;
import com.example.demo.entity.Student;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class StudentTest {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(5L, "金"));
students.add(new Student(9L, "张"));
students.add(new Student(11L, "李"));
students.add(new Student(3L, "王"));
students.add(new Student(1L, "虎"));
//外部实现排序
students.sort(Comparator.comparing(Student::getId).reversed());
for (Student student : students) {
System.out.println(student.getName());
}
}
}
</code></pre>