What is the best way to sort lists in Java?

Asked

Viewed 191 times

2

I have a list, for example:
I want to know how best to sort that 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);
    }

}
  • Even today, a question exactly like the one you are asking. Now see the question. The answer even uses a class Pessoa as you have in your question

  • In the other question the problem was to search, in this case it is to order. I think it is not duplicate (at least not the signed).

  • Yes indeed there is some difference in the sense that is order specifically and not seek

2 answers

6

Okay, the best best shape will depend on many factors, including the conjunction of the astral projection of the Sun in relation to Venus and where its shadow projects in the house of the Lunar Signs...

A way suitable to make this ordination is calling the Collections.sort.

To solution from @Isac I believe it is well decoupled, but there is a situation where, if the object is guaranteed to be comparable and absolutely manageable, there is no need to implement a Comparator anonymous/ephemeral.

In this case, the object needs to implement Comparable. So how are we dealing with the class Pessoa and if you wish to compare it to yourself, let us 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
}

All right, now you just need to call someone who knows how to sort out a list of comparable... and that’s 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 use normally the solution of @Isac, I usually do not have in many cases this absolute ordination.

  • It is not possible to make the program calculate what is the conjunction of the astral projection of the Sun in relation to Venus and where its shadow projects in the house of the Lunar Signs and with this information, choose the best implementation?

  • Maybe I can. Maybe you will find yourself in the halting problem, or else the discovery of optimal ordering is PSPACE or even R, I particularly when I can determine the problem class of optimal ordering. Imagine, the list that comes to me is a linked list? Or a set of arrays of variable sizes linked in only one direction? Or is it actually a balanced binary tree that you traverse in preorder? And will the data distribution make quicksort better than timsort? Or should I use a bucketsort with a heapsort inside each Bucket mixing everything with shellsort afterwards?

  • Not to mention "better for who"? What if the person doing the maintenance in the system doesn’t understand the fractal deviation calculations of the data entropy and makes a mistake? Should I make better code for the computer to process or for the human to understand? And for which computer to process better? If it is costly to access external memory, I should try to do several small sorting on the few registers available and then put it all together?

  • There is also the case that, perhaps, it is cheaper computationally speaking to go to the heuristic of always executing a shellsort than to calculate the astral projection and then still apply an ordination...

5

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

I will show you one using Amblas and based on the internal algorithm of sort for ArrayList. To order only by nome 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()));
    }
}

Exit:

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

In which here he sees that the ordination of the people is based on the comparison of their names, since it is called the compareTo of the name of p1, the first person, to p2.

See this example in Ideone

If you want to sort by name and for each name equal sort by age you already have to elaborate a little in the sorting method:

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

Note that the compareTo return 0 when both Strings are the same.

See also this example in Ideone

Documentation:

  • 1

    Use the diamond syntax and swap ArrayList<Pessoa> for ArrayList<>. I just don’t recommend leaving it static because it’s not one of the best programming practices to use the static for this (use as local variable same).

  • Thanks for the comment. The syntax of the diamond I always do as indicated, but this married one really passed. As for the static, it was really to try to maintain the same structure, although in the class that has the main, but I agree it’s not much practice, so I changed it too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.