对象排序得到方式
java实现 list 排序的方式,有三种
① 对象实现Comparable 接口,然后代码里直接调用Collections.sort(list)
②使用内部类Comparator
③使用stream.sort
代码如下
实现Comparable接口的实体类
@Data
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student s1) {
return this.age - s1.age;
}
}
没实现Comparable接口的实体类
@Data
public class Bag {
private int num;
private String name;
public Bag(int num, String name) {
this.num = num;
this.name = name;
}
}
几种排序的方式都在下面了:
public class testSort {
public static void main(String[] args) {
List<Student> list1 = new ArrayList<>();
Student s1 = new Student("张三", 15);
Student s2 = new Student("李四", 13);
Student s3 = new Student("王五", 14);
Student s4 = new Student("李二麻子", 22);
Student s5 = new Student("赵六", 31);
list1.add(s1);
list1.add(s2);
list1.add(s3);
list1.add(s4);
list1.add(s5);
Collections.sort(list1);
for (Student student : list1) {
System.out.println(student.getName() + "----" + student.getAge());
}
System.out.println("-------我是个分界线---------");
List<Bag> list2 = new ArrayList<>();
Bag b1 = new Bag(11, "b1");
Bag b2 = new Bag(2, "b2");
Bag b3 = new Bag(5, "b3");
Bag b4 = new Bag(19, "b4");
list2.add(b1);
list2.add(b2);
list2.add(b3);
list2.add(b4);
// 可以使用lamda表达式写法
Collections.sort(list2 ,(p1, p2) ->{return p1.getNum()-p2.getNum();});
/* 可以采取匿名内部类写法
Collections.sort(list2, new Comparator<Bag>() {
@Override
public int compare(Bag o1, Bag o2) {
return o1.getNum() - o2.getNum();
}
});
*/
for (Bag bag : list2) {
System.out.println(bag.getName() + "----" + bag.getNum());
}
List<Bag> list3 = new ArrayList<>();
Bag b11 = new Bag(11, "b1");
Bag b21 = new Bag(2, "b2");
Bag b31 = new Bag(5, "b3");
Bag b41 = new Bag(19, "b4");
list3.add(b11);
list3.add(b21);
list3.add(b31);
list3.add(b41);
// 这个stream。sort一定要接受返回值,否则源对象不变
list3 = list3.stream().sorted(Comparator.comparing(p -> p.getNum())).collect(Collectors.toList());
// 或者直接stream流里直接操作打印啥的
//list3.stream().sorted(Comparator.comparing(p -> p.getNum())).forEach(System.out::println);
System.out.println("--------我是个分界线--------");
for (Bag bag : list3) {
System.out.println(bag.getName() + "----" + bag.getNum());
}
}
}