How to sort arrays and lists in Java

In Java, there are several ways to sort arrays and lists. The most common way to sort an array or list is to use the sort() method of the Arrays class or the Collections class.

Here is an example of how to sort an array of integers using the Arrays.sort() method:

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] numbers = { 5, 2, 7, 1, 3 };

    // Sort the array
    Arrays.sort(numbers);

    // Print the sorted array
    for (int number : numbers) {
      System.out.println(number);
    }
  }
}

This will output the following:

1 2 3 5 7

Here is an example of how to sort a list of strings using the Collections.sort() method:

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

public class Main {
  public static void main(String[] args) {
    List<String> words = new ArrayList<>();
    words.add("apple");
    words.add("banana");
    words.add("cherry");

    // Sort the list
    Collections.sort(words);

    // Print the sorted list
    for (String word : words) {
      System.out.println(word);
    }
  }
}

This will output the following:

apple banana cherry

Both the Arrays.sort() and Collections.sort() methods use the merge sort algorithm to sort the array or list. This is a stable, efficient sorting algorithm that has a time complexity of O(n log n).

You can also use the sort() method with a custom comparator to sort the array or list according to a specific criterion. For example, you could sort a list of strings in descending order or sort a list of objects by a specific field.