什么都不用说了,直接上代码:
实体类代码:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ShopListInfoBean {
private String shopName = "";//店铺名
private Double shopDistance;//计算的距离
private Double shopCostPercent = 0.00;//价格比例
//构造
public ShopListInfoBean(String shopName,Double shopDistance,Double shopCostPercent){
shopName = this.shopName;
shopDistance = this.shopDistance;
shopCostPercent = this.shopCostPercent;
}
}
实现Comparator接口:
/**
* 当价格比例相同则比较距离,距离越小就越靠前
* @version 1.0
* @date 2021/1/19 14:52
*/
public class CompareByCost implements Comparator<ShopListInfoBean> {
@Override
public int compare(ShopListInfoBean o1, ShopListInfoBean o2) {
int result = -1;
Double shopCostPercent = o1.getShopCostPercent();
Double shopCostPercent1 = o2.getShopCostPercent();
Double shopDistance = o1.getShopDistance();
Double shopDistance1 = o2.getShopDistance();
if (shopCostPercent > shopCostPercent1) {
result = 1;
} else if (shopCostPercent.equals(shopCostPercent1)) {
if (shopDistance > shopDistance1) {
result = 1;
}
else if (shopDistance.equals(shopDistance1)){
result = 0;
}else {
return result;
}
} else {
return result;
}
return result;
}
}
测试一波:
public static void main(String[] args) {
ArrayList<ShopListInfoBean> shopListInfoBeans = new ArrayList<>();
shopListInfoBeans.add(new ShopListInfoBean("店铺一",2.3,15.0));
shopListInfoBeans.add(new ShopListInfoBean("店铺二",2.9,1.2));
shopListInfoBeans.add(new ShopListInfoBean("店铺三",3.4,8.23));
shopListInfoBeans.add(new ShopListInfoBean("店铺四",5.5,15.0));
shopListInfoBeans.add(new ShopListInfoBean("店铺五",7.3,12.4));
shopListInfoBeans.add(new ShopListInfoBean("店铺六",9.4,5.2));
System.out.println("===============================排序之前的=======================================");
for (ShopListInfoBean shopListInfoBean : shopListInfoBeans) {
System.out.println(shopListInfoBean.getShopName()+" "+"距离:"+shopListInfoBean.getShopDistance()+" "+"比例:"+shopListInfoBean.getShopCostPercent());
}
System.out.println("===============================排序之后的=======================================");
CompareByCost compareByCost = new CompareByCost();
shopListInfoBeans.sort(compareByCost);
for (ShopListInfoBean shopListInfoBean : shopListInfoBeans) {
System.out.println(shopListInfoBean.getShopName()+" "+"距离:"+shopListInfoBean.getShopDistance()+" "+"比例:"+shopListInfoBean.getShopCostPercent());
}
}
看结果: