array de strings
Para ordenar una array de strings en Java, podemos usar la función Arrays.sort() .
Java
// A sample Java program to // sort an array of strings // in ascending and descending // orders using Arrays.sort(). import java.util.Arrays; import java.util.Collections; public class SortExample { public static void main(String[] args) { String arr[] = { "practice.geeksforgeeks.org", "quiz.geeksforgeeks.org", "code.geeksforgeeks.org" }; // Sorts arr[] in ascending order Arrays.sort(arr); System.out.printf("Modified arr[] : \n%s\n\n", Arrays.toString(arr)); // Sorts arr[] in descending order Arrays.sort(arr, Collections.reverseOrder()); System.out.printf("Modified arr[] : \n%s\n\n", Arrays.toString(arr)); } }
Producción:
Arr modificado[] :
Arr modificado[]:
[quiz.geeksforgeeks.org, Practice.geeksforgeeks.org, code.geeksforgeeks.org]
ArrayLista De Strings
Si tenemos un ArrayList para ordenar, podemos usar Collections.sort()
Java
// A sample Java program to sort // an arrayList of strings // in ascending and descending // orders using Collections.sort(). import java.util.ArrayList; import java.util.Collections; public class SortExample { public static void main(String[] args) { ArrayList<String> al = new ArrayList<String>(); al.add("practice.geeksforgeeks.org"); al.add("quiz.geeksforgeeks.org"); al.add("code.geeksforgeeks.org"); // Sorts ArrayList in ascending order Collections.sort(al); System.out.println( "Modified ArrayList : \n" + al); // Sorts arr[] in descending order Collections.sort(al, Collections.reverseOrder()); System.out.println( "Modified ArrayList : \n" + al); } }
Producción:
ArrayList modificado:
ArrayList modificado:
[quiz.geeksforgeeks.org, Practice.geeksforgeeks.org, code.geeksforgeeks.org]