搜尋此網誌

2014年11月18日 星期二

【Android】sorting listview

ref:sorting listview in android

public class Team {
   private int points;
   private String name;

public Team(String n, int p) {
    name = n;
    points = p;
}

public int getPoints() {
    return points;
}

public String getName() {
    return name;
}

public static void main(String[] args) {
    List<Team> lteams = new ArrayList<Team>();

    lteams.add(new Team("FC Barcelona", 0));
    lteams.add(new Team("Arsenal FC", 2));
    lteams.add(new Team("Chelsea", 3));

    Collections.sort(lteams, new MyComparator());

    for (Team lteam : lteams) {
        System.out.println(lteam.name + ": " + lteam.points + " points");
    }
}
}
class MyComparator implements Comparator<Team> {
@Override
public int compare(Team o1, Team o2) {
    if (o1.getPoints() > o2.getPoints()) {
        return -1;
    } else if (o1.getPoints() < o2.getPoints()) {
        return 1;
    }
    return 0;
}}
Output:
Chelsea: 3 points
Arsenal FC: 2 points
FC Barcelona: 0 points

沒有留言: