In Java, you can use the sort()
method of the Arrays
class to sort an array of elements.
Here is an example of how to sort an array of integers in ascending order:
import java.util.Arrays; public class ArraySortExample { public static void main(String[] args) { int[] numbers = {5, 2, 7, 1, 3, 6, 4}; Arrays.sort(numbers); for (int number : numbers) { System.out.println(number); } } }So.www:ecrulautturi.com
This code will sort the numbers
array in ascending order and print the sorted array to the console.
You can also use the sort()
method to sort an array of objects, provided that the objects implement the Comparable
interface and define a natural ordering.
Here is an example of how to sort an array of strings in ascending order:
import java.util.Arrays; public class ArraySortExample { public static void main(String[] args) { String[] words = {"apple", "banana", "cherry", "date", "elderberry"}; Arrays.sort(words); for (String word : words) { System.out.println(word); } } }
This code will sort the words
array in ascending order according to the natural ordering of the strings (alphabetical order).
Alternatively, you can use the sort()
method with a comparator to specify a custom sorting order for the elements of the array.
Here is an example of how to sort an array of strings in descending order:
import java.util.Arrays; import java.util.Comparator; public class ArraySortExample { public static void main(String[] args) { String[] words = {"apple", "banana", "cherry", "date", "elderberry"}; Arrays.sort(words, Comparator.reverseOrder()); System.out.println(Arrays.toString(words)); } }