1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
public class ListSortTest {
static class User { private String name; private Integer age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public User() { }
public User(String name, Integer age) { this.name = name; this.age = age; }
@Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; }
}
public static void main(String[] args) { List<User> users = new ArrayList<User>(); users.add(new User("mike", 21)); users.add(new User("mike", 11));
Collections.sort(users, new Comparator<User>() { public int compare(User arg0, User arg1) { int i = arg0.getName().compareTo(arg1.getName()); if (i == 0) { return arg0.getAge().compareTo(arg1.getAge()); } return i; } });
for (User user : users) { System.out.println(user.toString()); }
} }
|