To do this sort, you can use the method sort
class Collections
. Through it, you can create a block ordering logic:
List<Pontuacao> pontuacoes = new ArrayList<>();
pontuacoes.add(new Pontuacao(14, 6, 20));
pontuacoes.add(new Pontuacao(18, 3, 21));
pontuacoes.add(new Pontuacao(14, 6, 22));
pontuacoes.add(new Pontuacao(15, 7, 11));
Collections.sort(pontuacoes, new Comparator<Pontuacao>() {
@Override
public int compare(Pontuacao lhs, Pontuacao rhs) {
if(lhs.getPontos != rhs.getPontos)
return Integer.compare(lhs.getPontos(), rhs.getPontos());
else if(lhs.getVitorias() != rhs.getVitorias())
return Integer.compare(lhs.getVitorias(), rhs.getVitorias());
return Integer.compare(lhs.getSaldoDeGols(), rhs.getSaldoDeGols());
}
});
Your Score object can even implement the interface Comparable<T>
to make this code more organized:
class Pontuacao implements Comparable<Pontuacao> {
private int pontos;
private int vitorias;
private int saldoDeGols;
public Pontuacao(int pontos, int vitorias, int saldoDeGols) {
this.pontos = pontos;
this.vitorias = vitorias;
this.saldoDeGols = saldoDeGols;
}
public int getPontos() {
return pontos;
}
public void setPontos(int pontos) {
this.pontos = pontos;
}
public int getVitorias() {
return vitorias;
}
public void setVitorias(int vitorias) {
this.vitorias = vitorias;
}
public int getSaldoDeGols() {
return saldoDeGols;
}
public void setSaldoDeGols(int saldoDeGols) {
this.saldoDeGols = saldoDeGols;
}
@Override
public int compareTo(@NonNull Pontuacao another) {
if(another.getPontos() != getPontos())
return Integer.compare(another.getPontos(), getPontos());
else if(another.getVitorias() != getVitorias())
return Integer.compare(another.getVitorias(), getVitorias());
return Integer.compare(another.getSaldoDeGols(), getSaldoDeGols());
}
}
So, Sort gets simplicate:
List<Pontuacao> pontuacoes = new ArrayList<>();
pontuacoes.add(new Pontuacao(14, 6, 20));
pontuacoes.add(new Pontuacao(18, 3, 21));
pontuacoes.add(new Pontuacao(14, 6, 22));
pontuacoes.add(new Pontuacao(15, 7, 11));
Collections.sort(pontuacoes);
We were teaching the OP to fish instead of giving the fish... and also the logic of the comparison is incorrect.
– Piovezan
...or not. L:^)
– Piovezan
What are setters for? To be able to change the score after the list has been ordered and thus invalidate the ordering? Since you suggested the full code, I suggest suggesting an immutable class for the Score object.
– Caffé
@Caffé, the setters are results of a class generation plugin with getters/setters that I used to create the example. I did not bother to remove them, or create the class in hand. I apologize for creating the answer with code. If you like, I remove
– Igor Castañeda Ferreira
There’s nothing to be sorry about, @Igorcastañedaferreira. The answer is yours (you say it) and it’s good.
– Caffé