Sorting an ArrayList in Java
Sorting is a way to arrange elements (objects) of a list or array in a certain order. The order may be in ascending or descending order. Another useful class in java.util package.
the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:
Example:- Sort an Array by using Strings:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<String> mobiles = new ArrayList<String>();
mobiles.add("Samsung");
mobiles.add("Apple");
mobiles.add("Nokia");
mobiles.add("Sony");
Collections.sort(mobiles); // Sort mobiles
for (String x : mobiles) {
System.out.println(x);
}
}
}
Example:- Sort an Array by using Integers:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> newNumbers = new ArrayList<Integer>();
newNumbers.add(393);
newNumbers.add(150);
newNumbers.add(270);
newNumbers.add(364);
newNumbers.add(908);
newNumbers.add(192);
Collections.sort(newNumbers); // Sort newNumbers
for (int x : newNumbers) {
System.out.println(x);
}
}
}
Keywords: