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:
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– Isac
Possible duplicate of How to create an element search method in an Arraylist?
– Renan Rodrigues
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).
– Gustavo Fragoso
Yes indeed there is some difference in the sense that is order specifically and not seek
– Isac