簡體   English   中英

根據鍵對Java對象排序

[英]Sort java object based on a key

我有一個數據列表,我需要按照以下方式對job_status下的pre_release進行有效排序,僅適用於已run對象: 1

"FAILED", "WARNING", "SUCCESS"

我正在嘗試使用冒泡排序,但需要幫助

//compareData contains list of object which needs to be sorted
List<HashMap<String, Object>> compareData = new ArrayList<HashMap<String, Object>>();

HashMap<String, Object> tempObj = new HashMap<String, Object>();
for (int i=0; i<compareData.size(); i++) {
    for (int j=1; i<(compareData.size() - 1); j++) {

        if (Integer.parseInt(compareData.get(j-1).get(JOB_STATUS_CODE).toString()) > Integer.parseInt(compareData.get(j).get(JOB_STATUS_CODE).toString())) {
            tempObj = compareData.get(j-1);
            //compareData.get(j-1) = compareData.get(j);

        }
    }
}

compareData

[{
    "pre_release": [{
        "message": "The environment GYAN-WIN2008-64-SP2-DC-1 used by this connection is inactive.",
        "start_time": "2015-05-27T22:45:25.000-07:00",
        "run": "1",
        "job_status": "FAILED",
        "job_status_code": "3"
    }, {
        "message": "The environment GYAN-WIN2008-64-SP2-DC-1 used by this connection is inactive.",
        "start_time": "2015-05-27T22:00:25.000-07:00",
        "run": "2",
        "job_status": "FAILED",
        "job_status_code": "3"
    }, {
        "message": "The environment GYAN-WIN2008-64-SP2-DC-1 used by this connection is inactive.",
        "start_time": "2015-05-27T21:15:25.000-07:00",
        "run": "3",
        "job_status": "FAILED",
        "job_status_code": "3"
    }],
    "task_name": "DB to DB xxx.yyy.42.62_2",
    "task_id": "000ABC0G000000000007",
    "production": {
        "message": "The environment Redhat Linux used by this connection is inactive.",
        "start_time": "2015-05-21T05:50:05.000-07:00",
        "job_status": "FAILED",
        "job_status_code": "3"
    }
} {
    "pre_release": [{
        "message": "The environment Redhat Linux used by this connection is inactive.",
        "start_time": "2015-05-21T05:50:05.000-07:00",
        "run": "1",
        "job_status": "FAILED",
        "job_status_code": "3"
    }, {
        "message": "The environment Redhat Linux used by this connection is inactive.",
        "start_time": "2015-05-21T05:45:05.000-07:00",
        "run": "2",
        "job_status": "FAILED",
        "job_status_code": "3"
    }, {
        "message": "The environment Redhat Linux used by this connection is inactive.",
        "start_time": "2015-05-21T05:40:05.000-07:00",
        "run": "3",
        "job_status": "FAILED",
        "job_status_code": "3"
    }],
    "task_name": "IPS_WS_Test",
    "task_id": "000ABC0K000000000096",
    "production": {
        "message": null,
        "start_time": "2015-02-02T13:05:00.000-08:00",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }
}, {
    "pre_release": [{
        "message": null,
        "start_time": "2015-02-02T13:05:00.000-08:00",
        "run": "1",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }, {
        "message": null,
        "start_time": "2015-02-02T13:00:00.000-08:00",
        "run": "2",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }, {
        "message": null,
        "start_time": "2015-02-02T12:55:00.000-08:00",
        "run": "3",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }],
    "task_name": "Logan josh mct win",
    "task_id": "000ABC0Z00000000009V",
    "production": {
        "message": "No errors encountered.",
        "start_time": "2015-05-19T13:31:28.000-07:00",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }
}, {
    "pre_release": [{
        "message": null,
        "start_time": "2015-05-14T07:27:10.000-07:00",
        "run": "1",
        "job_status": "WARNINGS",
        "job_status_code": "2"
    }, {
        "message": "Target field [MD_COntact__c] does not exist in the object [onlytesting__c].",
        "start_time": "2015-05-14T07:25:25.000-07:00",
        "run": "2",
        "job_status": "FAILED",
        "job_status_code": "3"
    }, {
        "message": "Target field [MD_COntact__c] does not exist in the object [onlytesting__c].",
        "start_time": "2015-05-14T07:24:55.000-07:00",
        "run": "3",
        "job_status": "FAILED",
        "job_status_code": "3"
    }],
    "task_name": "Lambba",
    "task_id": "000ABCI0000000002XP",
    "production": {
        "message": null,
        "start_time": "2015-05-14T07:27:10.000-07:00",
        "job_status": "WARNINGS",
        "job_status_code": "2"
    }
}, {
    "pre_release": [{
        "message": "No errors encountered.",
        "start_time": "2015-05-19T13:31:28.000-07:00",
        "run": "1",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }, {
        "message": "No errors encountered.",
        "start_time": "2015-05-19T13:12:15.000-07:00",
        "run": "2",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }, {
        "message": "No errors encountered.",
        "start_time": "2015-05-19T12:51:50.000-07:00",
        "run": "3",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }],
    "task_name": "chahamedidata_baja2",
    "task_id": "000ABC0I000000000301",
    "production": {
        "message": "[ERROR] com.baja.api.bajaServiceQueryOperationTimeIntervalFaultFaultFaultMessage: Query is limited to 1 request every 250 milliseconds (there have been 64.2 milliseconds since the last request)",
        "start_time": "2015-05-19T13:20:05.000-07:00",
        "job_status": "SUCCESS",
        "job_status_code": "1"
    }
}]

更新

所以我做了下面的事情,但是我Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!得到了Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!

Collections.sort(compareData, new Comparator<HashMap<String, Object>>() {
    @SuppressWarnings("unchecked")
    @Override
    public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
        // TODO Auto-generated method stub
        int i = 0;
        ArrayList<?> firstArray = (ArrayList<?>) o1.get(PRE_RELEASE);
        ArrayList<?> secondArray = (ArrayList<?>) o2.get(PRE_RELEASE);
        do {
            //System.out.println (((HashMap<String,Object>) firstArray.get(i)).get("run"));
            if (((HashMap<String,Object>) firstArray.get(i)).get("run").equals("1")) {
                if (((HashMap<String,Object>) firstArray.get(i)).get(JOB_STATUS).equals(((HashMap<String,Object>) secondArray.get(i)).get(JOB_STATUS))) {
                    return 0;
                } else {
                    if (((HashMap<String,Object>) firstArray.get(i)).get(JOB_STATUS).equals("FAILED")) 
                        return -1;
                    else if (((HashMap<String,Object>) firstArray.get(i)).get(JOB_STATUS).equals("WARNING")) {
                        return ((HashMap<String,Object>) firstArray.get(i)).get(JOB_STATUS).equals("FAILED") ? 1 : -1;
                    }
                    else {
                        return 1;
                    }
                }
            }
            i++;
        } while (i < firstArray.size());
        return 0;
    }
});

這個:

for (int j=1; i<(compareData.size() - 1); j++)

應該是

for (int j=1; j<(compareData.size() - 1); j++)

注意( i > j

您不只是對集合進行排序。 您首先要對其進行過濾(run = 1),然后對剩下的內容進行排序。

讓我們釋放一些Java8。 我假設您的pre_release集合已排序,因為在您的示例中,數據run = 1始終是第一個

List<MyItems> list = new LinkedList<>();
//Populate your list somehow.
list.stream()
.sorted((x1, x2) -> {
  String status1 = x1.pre_release[0].job_status;
  String status2 = x2.pre_release[0].job_status;
  if (x1.equals(x2)) return 0;
  else {
    if (x1.equals("FAILED")) {
      return -1;
    }
    else if (x1.equals("WARNING")) {
      return x2.equals("FAILED") ? 1 : -1;
    }
    else {
      return 1;
    }
  }
})
.collect(Collectors.toList());

如果不是這種情況,那么您需要更改分配status1和status2的代碼以搜索run = 1;

比較器需要尊重比較的可傳遞性。 意思是如果a=bb=ca=c ,與><相同。 在太多情況下,您的實現只是返回0 我建議您研究以下方法:

    List<HashMap<String, Object>> compareData = new ArrayList<>();
    Collections.sort(compareData, new Comparator<HashMap<String, Object>>() {
        @SuppressWarnings("unchecked")
        @Override
        public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
            ArrayList<?> firstArray = (ArrayList<?>) o1.get(PRE_RELEASE);
            ArrayList<?> secondArray = (ArrayList<?>) o2.get(PRE_RELEASE);

            Object firstRun1 = null;
            for (Object firstRun : firstArray) {
                if (((HashMap<String,Object>) firstRun).get("run").equals("1")) {
                    firstRun1 = firstRun;
                    break;
                }
            }

            Object secondRun1 = null;
            for (Object secondRun : secondArray) {
                if (((HashMap<String,Object>) secondRun).get("run").equals("1")) {
                    secondRun1 = secondRun;
                    break;
                }
            }

            if (firstRun1 == secondRun1) {
                return 0;
            }
            else if (firstRun1 == null) {
                return -1;
            }
            else if (secondRun1 == null) {
                return 1;
            }
            else {
                String firstStatus = (String) ((HashMap<String,Object>) firstRun1).get(JOB_STATUS);
                String secondStatus = (String) ((HashMap<String,Object>) secondRun1).get(JOB_STATUS);

                return toNum(firstStatus).compareTo(toNum(secondStatus));
            }
        }
    });

toNum方法:

Integer toNum(String status) {
    return "FAILED".equals(status) ? 0 : ("WARNING".equals(status) ? 1 : 2);
}

對不起,我無法測試它,因為我缺少一些代碼。

現在另一個建議:此代碼中有太多未經檢查的轉換和轉換。 我建議您直接使用某個JSONObject來解析Json時框架可能會返回給您,或者您將業務對象映射到真實的POJO中,而不是Maps和Objects列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM