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

Tutorial Básico de Java

Controle de Fluxo Java

Java Arrays

Java Orientado a Objetos (I)

Java Orientado a Objetos (II)

Java object-oriented (III)

Tratamento de Exceção do Java

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/)

Java Reader/Writer

Java other 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 Saída

ArrayList Não Ordenado: [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 to perform sorting in the opposite order using the Comparator interface.

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);
        //Os elementos são ordenados em ordem inversa
        if (value > 0) {
            return -1;
        }
        else if (value < 0) {
            return 1;
        }
        else {
            return 0;
        }
    }
}

Resultados de Saída

ArrayList Não Ordenado: [4, 2, 3]
Classificação Natural: [2, 3, 4]
Classificação Personalizada: [4, 3, 2]

No exemplo acima, usamos o método sort() e CustomComparator como parâmetro.

Aqui, CustomComparator é uma classe que implementa a interface Comparator. Saiba mais sobre a interface Java Comparator.

Então, reescreva o método compare(). Este método agora ordenará os elementos em ordem inversa.