Research breakthrough possible @S-Logix pro@slogix.in

Office Address

Social List

How to Sort Numbers List of Items in Java?

Sort Numbers in Java

Condition for Sorting Numbers List of Items in Java

  • Description: To sort a list of numbers in Java, the Collections.sort() method from the java.util package can be used for a list that implements the List interface, such as an ArrayList. This method sorts the numbers in ascending order by default. If descending order is required, a custom comparator can be used with Collections.sort() or List.sort(). Additionally, for more complex sorting or when sorting primitive arrays, Arrays.sort() can be used. Both Collections.sort() and Arrays.sort() use efficient sorting algorithms (like TimSort for lists) and provide in-place sorting, meaning the original list or array is modified directly. For sorting in a custom order, a Comparator can be created to define the specific criteria for comparison.
Sample Source Code
  • # SortingNumbers.java
    package JavaSamples;

    import java.util.ArrayList;
    import java.util.Collections;

    public class SortingNumbers {

    public static void main(String arg[]) {
    ArrayList numbers = new ArrayList<>();
    numbers.add(5);
    numbers.add(2);
    numbers.add(8);
    numbers.add(1);

    Collections.sort(numbers);
    System.out.println("Sorted in ascending order: " + numbers);

    Collections.sort(numbers, Collections.reverseOrder());
    System.out.println("Sorted in descending order: " + numbers);
    }
    }
Screenshots
  • STEP 1: To display the results for ascending order and descending order, the sorted numbers are shown.
  • Ascending order of numbers.