Comparator ArrayList JSP Object

2

I'm having trouble implementing the Comparator method, to sort the ArrayList of Objects.

I have a class of Entrepreneurship. Whereafter, I create an ArrayList, which is populated from a content manager system.

I added the compareTo method, and it sorts by the Area attribute. But now I also need you to order by quantity of rooms, and toilets.

How could I do this?

Here is the current quote:

    <%! 
public class Empreendimento implements Comparable<Empreendimento>{

     //possui atributos, gets, sets e construtor

        public int compareTo(Empreendimento Emp) {
            if (this.menorArea < Emp.getMenorArea()) {
                return -1;
            }
            if (this.menorArea > Emp.getMenorArea()) {
                return 1;
            }
            return 0;
        }
%>

After the content manager, create the ArrayList with these objects. I make a filter, and then I order. Then I use this:

Collections.sort(ArrayResultadoBusca);
    
asked by anonymous 14.01.2016 / 13:31

1 answer

3

With Java 8 , there is a simple and clean solution to deal with multiple comparisons.

Lambda :

Comparator<Empreendimento> comparator = Comparator
        .comparing(e -> e.getMenorArea)
        .thenComparingInt(e -> e.getQuantidadeQuarto)
        .thenComparingInt(e -> e.getQuantidadeBanheiro);

Method Reference :

Comparator<Empreendimento> comparator = Comparator
        .comparing(Empreendimento::getMenorArea)
        .thenComparingInt(Empreendimento::getQuantidadeQuarto)
        .thenComparingInt(Empreendimento::getQuantidadeBanheiro);
  

It is not recommended to mix code html of view with Java code,   it is interesting to perform the comparison in a class and then pass   the result by a Expression Language (EL).

An alternative is to implement a Comparator that instead of passing the attributes by parameter, passes two classes of the same type and compares its attributes.

Ex :

Collections.sort(lista, new Comparator<Empreendimento>(){
    public int compare(Empreendimento e1, Empreendimento e2) {
        int comparacao = e1.getMenorArea().compareTo(e2.getMenorArea());
        if(comparacao != 0) {
           return comparacao;
        }

        comparacao = e1.getQuantidadeQuarto().compareTo(e2.getQuantidadeQuarto());
        if(comparacao != 0) {
           return comparacao;
        }

        return e1.getQuantidadeBanheiro().compareTo(e2.getQuantidadeBanheiro());     
    }
});

It is important to implement equals and hashCode in the template class, in this case Entrepreneurship .

    
14.01.2016 / 15:15