What is the best way to sort lists in Java?

2

I have a list, for example:
I want to know how best to sort this list by name and age respectively.

public class Pessoa{
    private String nome;
    private int idade;

    // gets e sets omitidos
}

public class PessoaNeg{
    private List<Pessoa> listaPessoas = new ArrayList<Pessoa>();

    public void adicionarPessoas(){
       Pessoa pessoa = new Pessoa();
       pessoa.setNome("João");
       pessoa.setIdade(10); 

       Pessoa pessoa = new Pessoa();
       pessoa.setNome("Filomena");
       pessoa.setIdade(11); 

       listaPessoas.add(pessoa);
    }

}
    
asked by anonymous 07.11.2017 / 01:33

2 answers

6
Okay, the better will depend on many factors, including the conjunction of the sun's astral projection to Venus and where its shadow projects into the home of Lunar Signs ...

An appropriate way to do this sorting is by calling Collections.sort .

The @Isac solution I think is well decoupled, but there is a situation where, if the object is guaranteed to be absolutely comparable and orderly, you do not have to implement an anonymous / ephemeral Comparator .

In this case, the object must implement Comparable . So, since we're dealing with the Pessoa class and if you want to compare it with yourself, let's do this:

public class Pessoa implements Comparable<Pessoa> {
    private String nome;
    private int idade;

    @Override
    public int compareTo(Pessoa outra) {
        int nomeCmp = nome.compareTo(outra.nome);
        // deu empate quanto aos nomes, então vai para o desempate de idade
        if (nomeCmp == 0) {
            return idade - outra.idade;
        }
        return nomeCmp;
    }

    // gets e sets omitidos
}
Now, all you have to do is call someone who can sort a comparable list ... And this is the Collections.sort(List<T extends Comparable<? super T>) .

Now, just call:

List<Pessoa> pessoas = new ArrayList<>();

// ... povoa a lista ...

Collections.sort(pessoas);

PS: I would normally use the @Isac solution, I do not usually have this absolute ordering .

    
07.11.2017 / 03:46
5

There are many ways to sort, being by hand or using functions already done. And there are several sorts of sorting algorithms. Each can be better or worse depending on the purpose and type of data it has.

I'll show one using lambdas and relying on the internal algorithm of sort to ArrayList . To sort only by nome you can do:

public class Main {
    public static void main(String[] args) {
       List<Pessoa> listaPessoas = new ArrayList<>();

       listaPessoas.add(new Pessoa("João", 10));
       listaPessoas.add(new Pessoa("Filomena", 11));
       listaPessoas.add(new Pessoa("Martim", 25));
       listaPessoas.add(new Pessoa("Ana", 21));
       listaPessoas.add(new Pessoa("Rui", 9));  

       listaPessoas.sort((p1,p2)->p1.getNome().compareTo(p2.getNome())); //ordenação
       listaPessoas.forEach(x->System.out.println(x.obterInformacoes()));
    }
}

Output:

Nome: Ana, Idade: 21
Nome: Filomena, Idade: 11
Nome: João, Idade: 10
Nome: Martim, Idade: 15
Nome: Rui, Idade: 9

Here you see that the ordering of people is based on the comparison of their names, since it is called compareTo of the name of p1 , the first person, for p2 .

See this example in Ideone

If you want to sort by name and for each name just sort by age already have to elaborate a bit on the sort method:

listaPessoas.sort((p1,p2)-> {
    int compNomes = p1.getNome().compareTo(p2.getNome());
    return compNomes == 0 ? p1.getIdade()-p2.getIdade():compNomes;
});

Note that compareTo returns 0 when both Strings are equal.

See this example on Ideone

Documentation:

07.11.2017 / 03:26