假設有一個包含學生姓名和成績的列表,需要按照成績從高到低的順序進行排序。可以使用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);
}
}
}