1.定义实体类
public class Commodity {
//种类、名称、价格、商家名称、月均销量
private String type;
private String name;
private double price;
private String shopName;
private int sales;
public Commodity() {
}
public Commodity(String type, String name, double price, String shopName, int sales) {
this.type = type;
this.name = name;
this.price = price;
this.shopName = shopName;
this.sales = sales;
}
//此处省略类属性的get set方法
public String toString(){
return "名称:"+this.getName()+",\t售价:"+this.getPrice()+",\t卖家:"+this.getShopName()+",\t月销量:"+this.getSales();
}
}
2.自定义排序的类
必须实现Comparator接口,按照类的sales销量排序
boolean 表示升序还是降序,false降序 true升序
public class SalesComparator implements Comparator<Commodity> {
boolean is_Ascend;
public SalesComparator(boolean b){
this.is_Ascend = b;
}
public int compare(Commodity com1,Commodity com2) {
if(is_Ascend) {
return (int)(com1.getSales()-com2.getSales());
}else {
return (int)(com2.getSales()-com1.getSales());
}
}
}
3.main主程序调用sort方法
public static void main(String[] args) {
//准备一个集合,添加一些对象
ArrayList<Commodity> powedList = new ArrayList<>();
//忽略添加对象的过程
powedList.add...........
//排序
Collections.sort(powedList,new SalesComparator(false));
//显示粉饼销量前3名
System.out.println("\n粉饼分析结果如下:");
for (int i =0 ;i<powedList.size();i++){
System.out.println("销售量第"+(i+1)+"名的是:"+powedList.get(i).toString());
}
}