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: