Sorting an Array

2

I have my class ItemList

    public class ItemListPropaganda {

        private int iconeRid;
        private String texto;
        private int valor;

        public ItemListPropaganda(String texto, int iconeRid, int valor) {
            this.texto = texto;
            this.iconeRid = iconeRid;
            this.valor = valor;
        }

        public int getIconeRid() {
            return iconeRid;
        }

        public void setIconeRid(int iconeRid) {
            this.iconeRid = iconeRid;
        }

        public String getTexto() {
            return texto;
        }

        public void setTexto(String texto) {
            this.texto = texto;
        }

        public int getvalor() {
            return valor;
        }

        public void setvalor(int valor) {
            this.valor = valor;
        }
}

I have in my main class:

private ArrayList<ItemListPropaganda > itens;

How can I do to sort by value?

    
asked by anonymous 15.10.2014 / 18:28

1 answer

4

You can implement the Comparator interface and use it for Collections to sort your list.

For example, in API 19:

Collections.sort(itens, new Comparator<ItemListPropaganda>() {

            @Override
            public int compare(ItemListPropaganda o1, ItemListPropaganda o2)
            {
                return Integer.compare(o1.getValor(), o2.getValor());
            }
});

For compatibility purposes with APIs less than Integer.compare(arg1, arg2) (only available from API 19) should be avoided, as below:

Collections.sort(itens, new Comparator<ItemListPropaganda>() {

            @Override
            public int compare(ItemListPropaganda o1, ItemListPropaganda o2)
            {
                if(o1.getValor() < o2.getValor()) {
                    return -1;
                } else if (o1.getValor() == o2.getValor()) {
                    return 0;
                } else {
                    return 1;
                }
            }
});

With this, your list will be sorted according to the attribute you want.

    
15.10.2014 / 18:41