不多说,记住2点, 直接上代码(下面是降序):
package mall; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestSort2 { public static void main(String[] args) { List<Test> list = new ArrayList<Test>(); String [] n = {"a", "b", "c", "d", "e", "f", "g" , "h" , "i", "j", "k"}; double [] d = {0, 0, 34581, 0, 22017, 20807, 0 , 0 , 20443.2, 44457,0}; double [] a = {400, 0, 400, 200, 150, 400, 600, 300, 200, 500, 0}; for (int i = 0; i < a.length; i++) { Test s = new Test(n[i], d[i], a[i]); list.add(s); } //假如A的值大于B,你返回1 ,这样调用Collections.sort()方法就是升序 //假如A的值大于B,你返回-1,这样调用Collections.sort()方法就是降序 Collections.sort(list, new Comparator<Test>() { //总销售额(大->小) public int compare(Test o1, Test o2) { if(o1.getTotalPrice().compareTo(o2.getTotalPrice()) == 1) return -1; return 0; } }); for (int i = 0; i < list.size(); i++) { Test s = list.get(i); System.out.println("价格:"+s.getTotalPrice() + " , 面积:" + s.getArea()); } } static class Test { private String name; private Double totalPrice; private Double area; public Test(String name, double totalPrice, double area){ this.name = name; this.totalPrice = totalPrice; this.area = area; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getTotalPrice() { return totalPrice; } public void setTotalPrice(Double totalPrice) { this.totalPrice = totalPrice; } public Double getArea() { return area; } public void setArea(Double area) { this.area = area; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)