To sort a list in ascending order in Java, you can use the Collections.sort()
method or the List.sort()
method.
In this example,
numbers
and initialize it with integer values.Collections.sort()
method with the numbers
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 3));
Collections.sort(numbers);
System.out.println("Sorted list in ascending order: " + numbers);
}
}
Sorted list in ascending order: [1, 2, 3, 5, 8]
In this example,
words
and initialize it with string values.Collections.sort()
method with the words
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("banana", "apple", "cherry"));
Collections.sort(words);
System.out.println("Sorted list in ascending order: " + words);
}
}
Sorted list in ascending order: [apple, banana, cherry]
In this tutorial, we learned How to Sort a List in Ascending Order in Java language with well detailed examples.