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集合框架对数据进行排序。你可以根据需要选择合适的排序方法。