Java集合框架提供了多種排序方法,可以根據不同的需求選擇合適的排序方式。以下是幾種常用的排序方法:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(34);
numbers.add(12);
numbers.add(67);
numbers.add(45);
Collections.sort(numbers);
System.out.println("Sorted list: " + numbers);
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(34);
numbers.add(12);
numbers.add(67);
numbers.add(45);
Collections.sort(numbers, Collections.reverseOrder());
System.out.println("Sorted list in descending order: " + numbers);
}
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(34);
numbers.add(12);
numbers.add(67);
numbers.add(45);
numbers.sort(Comparator.naturalOrder());
System.out.println("Sorted list: " + numbers);
}
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(34);
numbers.add(12);
numbers.add(67);
numbers.add(45);
numbers.sort(Comparator.reverseOrder());
System.out.println("Sorted list in descending order: " + numbers);
}
}
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(34);
numbers.add(12);
numbers.add(67);
numbers.add(45);
System.out.println("Sorted set: " + numbers);
}
}
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>(Comparator.reverseOrder());
numbers.add(34);
numbers.add(12);
numbers.add(67);
numbers.add(45);
System.out.println("Sorted set in descending order: " + numbers);
}
}
這些示例展示了如何使用Java集合框架對數據進行排序。你可以根據需要選擇合適的排序方法。