monsteruniversity0908 monsteruniversity0908 - 3 months ago 46
Java Question

Java: Sorting a List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>(dataMap.values())

I would like to ask how to sort this list of Map by it's values which is the Object itself

This is a code from my ServiceImpl:

List<Map<String, Object>> dataList = serviceRequestDataDao.findServiceRequestData(serviceRequestQuery);


...

Map<Long, Map<String, Object>> dataMap = toMap(dataList,customReportSetting.getReportType());


...

dataList = new ArrayList<Map<String,Object>>(dataMap.values());


The dataMap.values() are all the values that I have retrieved from the database. I tried to display it using this code since I want it to be sorted by Creation Date Value (from oldest to latest):

for (Map<String, Object> mapList : dataList){
for (Map.Entry<String, Object> entry : mapList.entrySet()){
String key = entry.getKey();
Object value = entry.getValue();

if (key.equals("Creation Date")){
System.out.println(value);
}
}
}


I just don't know how to sort the WHOLE list containing map of string (keys) and objects (values).

The output of Creation Date is like this:

05/17/2016 02:56:40 PM

Answer

To sort a List of objects that don't have a natural order (Map doesn't), you call Collections.sort(List<T> list, Comparator<? super T> c).

Assuming your Creation Date value is a java.sql.Timestamp, this is how:

Collections.sort(dataList, new Comparator<Map<String, Object>>() {
    @Override
    public int compare(Map<String, Object> row1, Map<String, Object> row2) {
        Timestamp createDate1 = (Timestamp) row1.get("Creation Date");
        Timestamp createDate2 = (Timestamp) row2.get("Creation Date");
        return createDate1.compareTo(createDate2);
    }
});

Or this shorter lambda version if you're on Java 8+:

Collections.sort(dataList, (row1, row2) -> {
    Timestamp createDate1 = (Timestamp) row1.get("Creation Date");
    Timestamp createDate2 = (Timestamp) row2.get("Creation Date");
    return createDate1.compareTo(createDate2);
});

Which of course can be shortened to:

Collections.sort(dataList, (r1,r2) -> ((Timestamp)r1.get("Creation Date")).compareTo((Timestamp)r2.get("Creation Date")));