java按X排序,但按Y打印
在我的java程序中,有一个名为salesperson
的类的对象
这些对象有一个名为sales
的属性和一个名为name
的属性
我想将销售价值与进行比较,找出最大的价值,然后打印出具有最高销售价值的对象的名称
我是怎么做到的
double highSales;
String highSalesString;
highSales=first.getJanSales();
highSalesString=first.getSName() +" "+ first.getTitle();
if (second.getJanSales()>highSales)
{
highSales=second.getJanSales();
highSalesString=second.getSName() +" "+ second.getTitle();
}
if (third.getJanSales()>highSales)
{
highSales=third.getJanSales();
highSalesString=third.getSName() +" "+ third.getTitle();
}
我觉得有一个更简单的方法来实现这一点
# 1 楼答案
Comparator
您只需要使用^{} 或相应地实现^{}
比如说
如果您只需要这一个条目,则不必对整个列表进行排序:
还有^{} 可以用来代替流
Comparable
如果您认为默认情况下按} :
sales
对SalesPerson
进行排序是合理的(所谓的自然顺序),您也可以让他们相应地实现^{然后您可以将它们放入一个排序的集合中,例如
TreeSet
,这样它就可以为您保持它们的排序了。但是请注意,此类集合通常不允许在人员已添加到集合中时修改sales
# 2 楼答案
我会跳过排序,因为你想要的似乎是拥有最大销售额的人的名字。假设您的销售人员在列表中,您可以按如下方式进行:
用于演示目的的记录(行为类似于类)
创建一些数据
max
返回一个Optional<SalesPerson>
李>印刷品
如果你不想使用流,你可以通过循环来实现
best