蓝桥杯每日一题-图书排序

这个题我一开始想着用Map类型,但是发现map类型没办法排序,于是各种尝试之后使用Book类+Comparable接口实现了这个功能。

题目链接如下:
图书排序

AC代码如下:

java 复制代码
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改
class Book implements Comparable{
	private Integer id;
	private Integer quan;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getQuan() {
		return quan;
	}
	public void setQuan(Integer quan) {
		this.quan = quan;
	}
	public Book(Integer id, Integer quan) {
		super();
		this.id = id;
		this.quan = quan;
	}
	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		Book book = (Book)o;
		if (this.quan-book.quan>0) {
			return 1;
		}
		if (this.quan-book.quan==0) {
			return this.id.compareTo(book.id);
		}
		
		return -1;
	}
	
}
public class Main {
    public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		TreeSet tSet = new TreeSet<>();
		for(int i=0;i<n;i++) {
			int id = scanner.nextInt();
			int quan = scanner.nextInt();
			tSet.add(new Book(id, quan));
		}
		Iterator iterator = tSet.iterator();
		while(iterator.hasNext()) {
			Book book = (Book) iterator.next();
			System.out.println(book.getId());
		}
	}
}
相关推荐
极客先躯几秒前
高级java每日一道面试题-2026年02月04日-实战篇[Docker]-如何在容器之间共享数据?
java·运维·网络·docker·容器·自动化·高级面试题
真实的菜几秒前
微服务架构痛点
java·微服务·架构
小楊不秃头2 分钟前
Spring:Bean的存储
java·spring·bean
西凉的悲伤2 分钟前
多线程彻底掌握 CompletableFuture:从入门到项目实战
java·多线程·future·completable·异步
用户298698530142 分钟前
Java 中的 HTML 解析:从文件读取、URL 抓取到数据提取
java·后端
plainGeekDev3 分钟前
ContentProvider → Room + Repository
android·java·kotlin
plainGeekDev8 分钟前
SQLite 手动升级 → Room Migration
android·java·kotlin
小欣加油10 分钟前
leetcode121买卖股票的最佳时机
数据结构·c++·算法·leetcode·职场和发展
带刺的坐椅11 分钟前
SolonCode(编码智能体)支持鸿蒙 PC
java·web·ai编程·harmonyos·soloncode·鸿蒙 pc
程序员二叉12 分钟前
【JVM】类加载全过程&双亲委派机制深度解析
java·jvm·面试