package com.kurumi.util;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class SortUtils {
public static <T> void sort(List<T> list, Map<String, String> sortMap) {
if (list == null || list.isEmpty() || sortMap == null || sortMap.isEmpty()) {
return;
}
Comparator<T> comparator = new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
int result = 0;
for (Map.Entry<String, String> entry : sortMap.entrySet()) {
String key = entry.getKey();
String order = entry.getValue().toLowerCase();
try {
Comparable<Object> value1 = (Comparable<Object>) o1.getClass().getMethod(getter(key)).invoke(o1);
Comparable<Object> value2 = (Comparable<Object>) o2.getClass().getMethod(getter(key)).invoke(o2);
if (value1 == null || value2 == null) {
if (value1 == null && value2 == null) {
result = 0;
} else if (value1 == null) {
result = order.equalsIgnoreCase("desc") ? -1 : 1;
} else {
result = order.equalsIgnoreCase("desc") ? 1 : -1;
}
} else {
result = value1.compareTo(value2);
}
if (result != 0) {
return order.equalsIgnoreCase("desc") ? -result : result;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
};
list.sort(comparator);
}
private static String getter(String fieldName) {
if (fieldName == null || fieldName.length() == 0) {
return null;
}
return "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
}
}