假设有一个包含学生姓名和成绩的列表,需要按照成绩从高到低的顺序进行排序。可以使用Java的Collections工具类来实现:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 72));
students.add(new Student("Cathy", 90));
Collections.sort(students, (s1, s2) -> s2.getScore() - s1.getScore());
for (Student student : students) {
System.out.println(student.getName() + ": " + student.getScore());
}
}
static class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
}
假设有一个包含字符串的列表,需要按照字母顺序进行排序。可以使用Java的Collections工具类来实现:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
strings.add("apple");
strings.add("banana");
strings.add("cherry");
Collections.sort(strings);
for (String str : strings) {
System.out.println(str);
}
}
}