Sorting an Array

Asked

Viewed 106 times

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 order by value ?

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 with lower Apis Integer.compare(arg1, arg2) (is 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.

  • am using API 19, could implement an example of this condition?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.