1 数组排序Arrays.sort
Java程序使用Arrays.sort()方法升序排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import java.util.Arrays; public class JavaSortExample { public static void main(String[] args) { Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 520, 1123, 366, 420 }; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); } }
|
逆序
1 2 3 4 5 6 7
| Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 520, 1123, 366, 420 };
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println(Arrays.toString(numbers));
|
部分排序
1 2 3 4 5 6 7 8
| Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 };
Arrays.sort(numbers, 2, 6);
System.out.println(Arrays.toString(numbers));
|
并发排序
它将数组分解为不同的子数组,并且每个子数组在different threads使用Arrays.sort()进行排序。 最终,所有排序的子数组将合并为一个数组。
1 2 3 4 5
| Arrays.parallelSort(numbers); Arrays.parallelSort(numbers, 2, 6); Arrays.parallelSort(numbers, Collections.reverseOrder());
|
不支持集合排序。转换为列表,然后排序,然后转换为集合。
不支持map排序。获取keyset,然后排序访问。
但是treeSet和TreeMap本身都是排序好的。
2 字符串排序方法
Stream API
使用Stream.sorted() API对字符串的字符进行排序的示例。
1 2 3 4 5 6 7
| String randomString = "adcbgekhs"; String sortedChars = Stream.of( randomString.split("") ) .sorted() .collect(Collectors.joining()); System.out.println(sortedChars);
|
Arrays.sort()
使用Arrays.sort()方法对字符串排序的示例。
1 2 3 4 5 6 7 8 9 10 11 12
| String randomString = "adcbgekhs";
char[] chars = randomString.toCharArray();
Arrays.sort(chars);
String sortedString = String.valueOf(chars); System.out.println(sortedChars);
|
3 ArraysList排序
自带的sort方法
1 2 3 4 5 6 7 8 9 10 11 12
| List<String> names = Arrays.asList("Alex", "Charles", "Brian", "David");
names.sort( Comparator.comparing( String::toString ) ); System.out.println(names);
names.sort( Comparator.comparing( String::toString ).reversed() ); System.out.println(names);
|
Collections.sort
1 2 3 4 5 6 7 8 9 10 11 12
| List<String> names = Arrays.asList("Alex", "Charles", "Brian", "David");
Collections.sort(names); System.out.println(names);
Collections.sort(names, Collections.reverseOrder()); System.out.println(names);
|
Stream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| List<String> names = Arrays.asList("Alex", "Charles", "Brian", "David");
List<String> sortedNames = names .stream() .sorted(Comparator.comparing(String::toString)) .collect(Collectors.toList()); System.out.println(sortedNames);
List<String> reverseSortedNames = names .stream() .sorted(Comparator.comparing(String::toString).reversed()) .collect(Collectors.toList()); System.out.println(reverseSortedNames);
|
4 ObjectSort
将Comparable&Comparator