Ordenar listas en Java Android

8:52 , 0 Comments

Si usas listas en tus aplicaciones de Android, el siguiente code snippet sirve para Ordenar items de objetos List en Java, dependiendo del campo se ordenarán.

Clase Person.java
public class Person {
    String gender;
    String name;
    int age;
    double height;
    double weight;

   public Person(String gender, String name, int age, double height, double weight) {
        this.gender = gender;
        this.name = name;
        this.age = age;
        this.height = height;
        this.weight = weight;
   }

//Getters
   public String getGender() {
       return this.gender;
   }
   public String getName() {
       return this.name;
   }
   public int getAge() {
       return this.age;
   }
   public double getHeight() {
       return this.height;
   }
   public double getWeight() {
       return this.weight;
   }
}

Llenar contenido de muestra
List people = new ArrayList<>();
people.add(new Person("F","Alice", 15, 160, 48));
people.add(new Person("F","Karen", 18, 140, 45)); 
people.add(new Person("MALE","Bob", 8, 90, 30)); 
people.add(new Person("MALE","John", 40, 180, 78)); 


Función para ordenar
class SortPersonaByAge implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.age - o2.age;
    }

}


Ordenar la lista Ascendente
Collections.sort(people,new SortPersonaByAge());


Ordenar la lista Descendente
Collections.sort(people, Collections.reverseOrder(new SortPersonaByAge()));

webserveis

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 comentarios: