aseolin
aseolin

Reputation: 1200

Merge two Comparator sort

I have the following Classes:

public class Orador {
  int id;
  int situacao;
  Expediente expediente;
}

public class Expediente {
  int id;
  int sequencia;
}

The attribute "situacao" can be (0, 1 or 2). The attribute "sequencia" can be (0, 1, 2, 3, 4, ...).

I want to sort some Orador objects: first by situacao, second by sequencia, but situacao = 1 must be que first one, followed by 0 and than 2.

I was able to do this with 2 Comparator class:

public class SequenciaExpedienteComparator implements Comparator<Orador> {
    @Override
    public int compare(Orador o1, Orador o2) {
        return o1.getExpediente().getSequencia().compareTo(o2.getExpediente().getSequencia());
    }
}

public class DiscursoRealizadoComparator implements Comparator<Orador> {
    @Override
    public int compare(Orador o1, Orador o2) {

        Integer situacaoOrador1 = ((Orador) o1).getSituacao().value();
        Integer situacaoOrador2 = ((Orador) o2).getSituacao().value();

        // situacao == 1 must be the first in the list
        if (situacaoOrador1 == 1) {
            return -1;
        }
        if (situacaoOrador2 == 1) {
            return 1;
        }
        return situacaoOrador1.compareTo(situacaoOrador2);
    }
}

So I'm calling two sorting methods:

Collections.sort(listaOradores, new SequenciaExpedienteComparator());
Collections.sort(listaOradores, new DiscursoRealizadoComparator());

This is working as expected, but I want to know if there's a way to do this using only one sorting method, i.e, merge this two comparator into one, in order to optimize the code.

Upvotes: 0

Views: 861

Answers (1)

Lothar
Lothar

Reputation: 5459

You can do it e.g. like this:

final static Comparator<Orador> comparator = new Comparator<Orador> {
    @Override
    public int compare(Orador o1, Orador o2) {
        if (o1.getSituacao() == 1) {
            return -1;
        }
        if (o2.getSituacao() == 1) {
            return 1;
        }
        int ret = Integer.compare(o1.getSituacao(), o2.getSituacao());
        if (ret != 0) {
            return ret;
        }
        return Integer.compare(o1.getExpediente().getSequencia(),
                               o2.getExpediente().getSequencia());
    }
}

I changed the code to avoid autoboxing (because I hate it ;-)

Upvotes: 1

Related Questions