How to compare objects by multiple fields

后端 未结 22 2575
暖寄归人
暖寄归人 2020-11-22 00:43

Assume you have some objects which have several fields they can be compared by:

public class Person {

    private String firstName;
    private String lastN         


        
22条回答
  •  一向
    一向 (楼主)
    2020-11-22 01:23

    //here threshold,buyRange,targetPercentage are three keys on that i have sorted my arraylist 
    final Comparator 
    
        sortOrder = new Comparator() {
                        public int compare(BasicDBObject e1, BasicDBObject e2) {
                            int threshold = new Double(e1.getDouble("threshold"))
                            .compareTo(new Double(e2.getDouble("threshold")));
                            if (threshold != 0)
                                return threshold;
    
                            int buyRange = new Double(e1.getDouble("buyRange"))
                            .compareTo(new Double(e2.getDouble("buyRange")));
                            if (buyRange != 0)
                                return buyRange;
    
                            return (new Double(e1.getDouble("targetPercentage")) < new Double(
                                    e2.getDouble("targetPercentage")) ? -1 : (new Double(
                                            e1.getDouble("targetPercentage")) == new Double(
                                                    e2.getDouble("targetPercentage")) ? 0 : 1));
                        }
                    };
                    Collections.sort(objectList, sortOrder);
    

提交回复
热议问题