/** * @author lautturi.com * Java example: android sort array list float/int */ import java.util.*; class Person{ String name; int age; public Person(String string, int i) { name = string; age = i; } public String getName() { return name; } public int getIntValue() { return age; } public int getAge() { return age; } } public class Lautturi { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Lautturi",6)); persons.add(new Person("Alan",13)); persons.add(new Person("Bob",25)); persons.add(new Person("James",22)); persons.add(new Person("Tom",22)); persons.add(new Person("Alan",23)); persons.add(new Person("Sally",23)); persons.add(new Person("Leo",29)); persons.add(new Person("Haley",27)); persons.add(new Person("Martin",18)); for (Person p : persons) { System.out.println(p.getName()+" "+p.getAge()); } Collections.sort(persons, new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { return Float.compare(((Person)o1).getIntValue(), ((Person)o2).getIntValue()); } }); System.out.println("--------sorted list by the age:--"); for (Person p : persons) { System.out.println(p.getName()+" "+p.getAge()); } } }
output:
Lautturi 6 Alan 13 Bob 25 James 22 Tom 22 Alan 23 Sally 23 Leo 29 Haley 27 Martin 18 --------sorted list by the age:-- Lautturi 6 Alan 13 Martin 18 James 22 Tom 22 Alan 23 Sally 23 Bob 25 Haley 27 Leo 29