0

I need to sort the products by High to Low & Low to High of its Price.I have done Low to High by using following code.But dont know how to implement High To Low?

Your answer is more appreciated...

 public static Comparator<Restaurant_Beam> strPriceFilterL2H = new Comparator<Restaurant_Beam>() {

      @Override
        public int compare(Restaurant_Beam lhs, Restaurant_Beam rhs) {
            int CompareResult = 0;
            if (Config.L2HFilterClicked == "L2H") {
                CompareResult = (int) Math.round(Double.parseDouble(lhs.getIG_SALES_PRICE()) - Double.parseDouble(rhs.getIG_SALES_PRICE()));

            } 
//Used else if for H2L.But did not get it as perfect

else if (Config.L2HFilterClicked == "H2L") {
                CompareResult = (int) Math.round(Double.parseDouble(lhs.getIG_SALES_PRICE()) + Double.parseDouble(rhs.getIG_SALES_PRICE()));

            }
            return CompareResult;
        }
    };

Change the second compare expression to this one:

CompareResult = (int) Math.round(Double.parseDouble(Double.parseDouble(rhs.getIG_SALES_PRICE()) - Double.parseDouble(lhs.getIG_SALES_PRICE()));

Also I'd like to point out a few things

  • consider doing Double comparison with epsilon
  • it's a good practice to check objects before comparing them
  • parsing each time you compare is really bad design. It would be better if you parse values somewhere in advance, consider changing your type. Currently it's not efficient.
4

1 回答 1

3

将第二个比较表达式更改为这个:

CompareResult = (int) Math.round(Double.parseDouble(Double.parseDouble(rhs.getIG_SALES_PRICE()) - Double.parseDouble(lhs.getIG_SALES_PRICE()));

另外我想指出几点

  • 考虑Double与 epsilon 进行比较
  • 在比较对象之前检查对象是一个好习惯
  • 每次比较时解析都是非常糟糕的设计。如果您提前在某处解析值会更好,考虑更改您的类型。目前效率不高。
于 2016-04-11T10:11:25.097 回答