对List集合中的元素进行排序
对List集合中的元素进行排序
经常会遇到对list中的元素进行排序,这时候就要使用Collections.sort()方法进行排序操作了。
如果 List中存放的是基本数据类型元素那很简单:
public static void main(String[] args) throws UnsupportedEncodingException{
ArrayList<Integer> strList = new ArrayList<>();
strList.add(5);
strList.add(2);
strList.add(1);
strList.add(4);
strList.add(3);
Collections.sort(strList);
System.out.println(strList.toString());
}
但是我们通常需要排序的情况基本都是list里存放的是对象类型,此时就不能这么简单的调用collections.sort()方法了:
public static void main(String[] args) throws UnsupportedEncodingException{
ArrayList<User> strList = new ArrayList<User>();
User user = new User();
user.setAge(30);
user.setRealname("张2");
strList.add(user);
User user1 = new User();
user1.setAge(20);
user1.setRealname("张1");
strList.add(user1);
User user2 = new User();
user2.setAge(40);
user2.setRealname("张3");
strList.add(user2);
for(int i=0; i<strList.size(); i++){
System.out.println(strList.get(i).getRealname()+":"+strList.get(i).getAge());
}
Collections.sort(strList, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
if(o1.getAge() < o2.getAge()){
return 1;
}else if(o1.getAge() == o2.getAge()){
return 0;
}else{
return -1;
}
}
});
System.out.println("#############");
for(int i=0; i<strList.size(); i++){
System.out.println(strList.get(i).getRealname()+":"+strList.get(i).getAge());
}
}