比较器练习(list,set,map...)



//java中对ArrayList进行排序,比较器练习
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
//保存学生信息
class StudentInfo{
 String name;
 int age;
 int score;
 public StudentInfo(String name, int age , int score){
  this.name = name;
  this.age = age;
  this.score = score;
 }
}
class SortByAge implements Comparator{
 public int compare(Object o1 , Object o2){
  StudentInfo stu1 = (StudentInfo)o1;//向下转型
  StudentInfo stu2 = (StudentInfo)o2;
  //升序Ascending order
//  return stu1.age - stu2.age;
  //逆序Discending order
  return stu2.age - stu1.age; 
  
 }
}
class SortByName implements Comparator{
 public int compare(Object o1 , Object o2){
  StudentInfo stu1 = (StudentInfo)o1;
  StudentInfo stu2 = (StudentInfo)o2;
  //字符串比较,按照字典序
  //升序
  return stu1.name.compareTo(stu2.name);
  //降序
//  return stu2.name.compareTo(stu1.name);
 }
}
class SortByScore implements Comparator{
 public int compare(Object o1 , Object o2){
  StudentInfo stu1 = (StudentInfo)o1;
  StudentInfo stu2 = (StudentInfo)o2;
  //升序
  return stu1.score - stu2.score;
  //降序
//  return stu2.score - stu1.score;
 }
}
public class Main{
    public static void main(String[] args){
     List<StudentInfo> list = new ArrayList<StudentInfo>();     
     list.add(new StudentInfo("zhangsan" , 23 , 45));
     list.add(new StudentInfo("lisi" , 32 , 53));
     list.add(new StudentInfo("lisi" , 32 , 52));
     list.add(new StudentInfo("wangwu" , 13 , 67));
     list.add(new StudentInfo("zhengliu" , 27 , 43));
     System.out.println("orginal:");
     for(StudentInfo stu : list){
      System.out.println("name :" + stu.name + "\tage :" + stu.age + "\tscore :" + stu.score);
     }
     Collections.sort(list, new SortByScore());
     System.out.println("after sort:");
     for(StudentInfo stu : list){
      System.out.println("name :" + stu.name + "\tage :" + stu.age + "\tscore :" + stu.score);
     }
    } 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值