English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriales básicos de Java

Control de flujo Java

Java arrays

Java orientado a objetos (I)

Java orientado a objetos (II)

Java object-oriented (III)

Manejo de excepciones en Java

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Other Java topics

Java sort() method

The sort() method of the collection framework uses the merge sort algorithm to sort the elements of the collection.

The merge sort algorithm is based on the divide and conquer rule. For more information about merge sort, please visit the merge sort algorithm page.

Let's take the sort() method as an example.

Example: sort in ascending order

import java.util.ArrayList;
import java.util.Collections;
class Main {
    public static void main(String[] args) {
        //Create an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        //Add element
        numbers.add(4);
        numbers.add(2);
        numbers.add(3);
        System.out.println("Unsorted ArrayList: ") + numbers);
        //Use the sort() method
        Collections.sort(numbers);
        System.out.println("Sorted ArrayList: ") + numbers);
    }
}

Resultados de salida

Unsorted ArrayList: [4, 2, 3]
Sorted ArrayList: [2, 3, 4]

As you can see, by default, sorting is performed in natural order (ascending). However, we can customize the sorting order of the sort() method.

Custom sorting order

In Java, you can customize the sort() method by using the Comparator interface to sort in reverse order.

Example: sort in descending order

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Main {
    public static void main(String[] args) {
        //Create an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        //Add element
        numbers.add(4);
        numbers.add(2);
        numbers.add(3);
        System.out.println("Unsorted ArrayList: ") + numbers);
        //Use the sort() method
        Collections.sort(numbers);
        System.out.println("Natural Sorting: ") + numbers);
        //Use the custom sort() method
        Collections.sort(numbers, new CustomComparator());
        System.out.println("Customized Sorting: ") + numbers);
    }
}
class CustomComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer animal1, Integer animal2) {
        int value = animal1.compareTo(animal2);
        //Los elementos se ordenan en orden inverso
        if (value > 0) {
            return -1;
        }
        else if (value < 0) {
            return 1;
        }
        else {
            return 0;
        }
    }
}

Resultados de salida

Unsorted ArrayList: [4, 2, 3]
Natural Sorting: [2, 3, 4]
Customized Sorting: [4, 3, 2]

En el ejemplo anterior, usamos el método sort() y CustomComparator como parámetro.

Aquí, CustomComparator es una clase que implementa la interfaz Comparator. Aprende más sobre la interfaz Java Comparator.

Luego, reescribe el método compare(). Este método ahora ordenará los elementos en orden inverso.