将学生按照成绩保存到集合中,并且名字叫tom的学生不管考多少分都位于班级的第一位

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class Test_10 {
	public static void main(String[] args) {
		//实例化集合对象,准备比较器 排序算法
		Set<Student1> coll = new TreeSet<>(new Comparator<Student1>() {
			//重写Comparator接口中的compate方法
			public int compare(Student1 o1, Student1 o2) { //o1新值 o2老值
				//先把成绩,降序排列
				int r = o2.getScore() - o1.getScore(); //成绩降序
				//如果成绩一样,名字 升序排列
				if (r == 0) {  
					r = o1.getName().compareTo(o2.getName()); //名字升序
				}
				//额外处理:
				//1  tom(新值) 与  其他
				if ("tom".equals(o1.getName()) && !"tom".equals(o2.getName())) {
					r = 1; //升序
				}
				//2    其他   与   tom(老值)
				else if (!"tom".equals(o1.getName()) && "tom".equals(o2.getName())) {
					r = -1; //降序
				}
				//3  tom(新值)  与   tom(老值)    
				if ("tom".equals(o1.getName()) && "tom".equals(o2.getName())) {
					r = o2.getScore() - o1.getScore(); //成绩降序
				}
				return r;
			}
		});
		//在coll集合中,add添加Student对象的信息
		coll.add(new Student1("hh",65));
		coll.add(new Student1("nihao",84));
		coll.add(new Student1("jack",69));
		coll.add(new Student1("jack",79));
		coll.add(new Student1("tom",74));
		coll.add(new Student1("tom",84));
		coll.add(new Student1("tom",76));
		coll.add(new Student1("hello",85));
		coll.add(new Student1("world",77));
		//遍历输出
		for (Student1 s : coll) {
			System.out.println(s);
		}
		
	}
}
//Student类 存学生成绩
class Student1{
	private String name;
	private int score;
	
	public Student1() {
		super();
	}
	public Student1(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}

	public String toString() {
		return "Student [name=" + name + ", score=" + score + "]";
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值