Java中集合的数字排乱,升,降序
(代码如下,需要练习请自取)
1.建Student类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Comparable<Student> {
private int id;
private String name;
private int score;
private String address;
/**
* 默认排序
*
* @param o the object to be compared.
* @return
*/
@Override
public int compareTo(Student o) {
//this a o b (a,b) -> a.id - b.id
return id - o.id;
}
}
2.建排序类(类名自定义)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Paixu {
public static void main(String[] args) {
//自定义对象 排序
List<Student> s = new ArrayList<>(List.of(
new Student(10, "李四", 30, "郑州"),
new Student(11, "张三", 90, "天津"),
new Student(12, "李丽", 60, "郑州"),
new Student(23, "张三丰", 80, "北京"),
new Student(36, "王五", 20, "郑州"),
new Student(100, "赵六", 10, "上海"),
new Student(9, "李强", 39, "上海"),
new Student(1, "李三", 99, "上海"),
new Student(11000, "李磊", 89, "上海")
));
System.out.println(s);
Collections.shuffle(s);
System.out.println(s);
//Collections.sort(s); 这一行有错误,Student对象没有实现排序接口的相关的方法
//Collections.sort(s,(a,b)->b.getId()-a.getId());
//System.out.println(s);
//Collections.sort(s,(a,b)->a.getName().compareTo(b.getName()));
//System.out.println(s);
//Collections.sort(s,(a,b)->b.getName().length() - a.getName().length());
//System.out.println(s);
//如果类实现了Comparable<cn.webrx.coll.Student>接口并实现了方法compareTo()
//根据id的升序
Collections.sort(s);
System.out.println(s);
Collections.sort(s,(o1,o2)->o2.getId()-o1.getId());
System.out.println(s);
结果如下