Sort Alphabetically in Java: Quick Guide
In Java, you can use the Arrays.sort() method to sort an array in alphabetical order, or use the Collections.sort() method to sort a list. Here is an example code:
- Sort the character array.
char[] arr = {'c', 'a', 'b'};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // 输出:[a, b, c]
- Sort the array of strings.
String[] arr = {"c", "a", "b"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // 输出:[a, b, c]
- Sort a list of strings.
List<String> list = new ArrayList<>();
list.add("c");
list.add("a");
list.add("b");
Collections.sort(list);
System.out.println(list); // 输出:[a, b, c]
Please note that the above code is sorted by default according to the Unicode values of the letters. If you need to sort according to a custom alphabetical order, you can use the Comparator interface to define the sorting rules.