实现数组升序,降序,乱序(数字数组,字符串数组,对象数组,字符串长度)
//数字数组
Integer[] i = new Integer[]{5, 4, 6, 8, 96, 51};
//升序
Arrays.sort(i);
System.out.println(Arrays.toString(i));
//降序
Arrays.sort(i, (a, b) -> b - a);
System.out.println(Arrays.toString(i));
//乱序
Arrays.sort(i, (a, b) -> Math.random() > .5 ? 1 : -1);
System.out.println(Arrays.toString(i));
//字符串数组
String[] y = {"中国", "java", "c++", "A股", "Bilibili"};
//升序
Arrays.sort(y);
System.out.println(Arrays.toString(y));
//降序
Arrays.sort(y, (a, b) -> b.compareTo(a));
System.out.println(Arrays.toString(y));
//乱序
Arrays.sort(y, (a, b) -> Math.random() > .5 ? 1 : -1);
System.out.println(Arrays.toString(y));
//对象数组
Student[] student = new Student[]{new Student(10, "王一", LocalDate.of(2001, 12, 13), 95), new Student(5, "李二", LocalDate.of(2005, 12, 13), 96), new Student(6, "张三", LocalDate.of(2008, 12, 13), 98), new Student(15, "范五", LocalDate.of(2007, 12, 13), 99), new Student(14, "葛四", LocalDate.of(2002, 12, 13), 91)};
//升序
Arrays.sort(student, (a, b) -> a.getId() - b.getId());
System.out.println(Arrays.toString(student) + "-".repeat(5));
//乱序
Arrays.sort(student, (a, b) -> Math.random() > .5 ? 1 : -1);
System.out.println(Arrays.toString(student) + "-".repeat(5));
//降序
Arrays.sort(student, (a, b) -> b.getBir().compareTo(a.getBir()));
System.out.println(Arrays.toString(student) + "-".repeat(5));
//升序
Arrays.sort(student, (a, b) -> b.getScore() - a.getScore());
System.out.println(Arrays.toString(student) + "-".repeat(5));
对象数组
public class Student implements Comparable<Student> {
private int id;
private String name;
private LocalDate bir;
private int score;
@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + ", bir=" + bir + ", score=" + score + '}';
}
public Student() {
}
public Student(int id, String name, LocalDate bir, int score) {
this.id = id;
this.name = name;
this.bir = bir;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBir() {
return bir;
}
public void setBir(LocalDate bir) {
this.bir = bir;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Student o) {
return 0;
}
}