* 1、一个User类有String name int age
* ArrayList<User> 存储数据然后按 年龄倒序打出
*
*/
public class Test1 {
public static void main(String[] args) {
ArrayList<User> list=new ArrayList<User>();
list.add(new User("张三", 23));
list.add(new User("钱七", 27));
list.add(new User("王武", 25));
list.add(new User("李四", 24));
list.add(new User("赵六", 26));
toString(list);
}
public static void toString(List<User> list) {
TreeSet<User> ts=new TreeSet<User>(new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
int num=u2.getAge()-u1.getAge();
return num==0?u2.getName().compareTo(u1.getName()):num;
}
});
ts.addAll(list);
list.clear();
list.addAll(ts);
for (User user : list) {
System.out.println(user.getName()+"---"+user.getAge());
}
}
}
|
|