package com.fancy.framework.core.util;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
@SuppressWarnings("unchecked")
public final class JsonSortUtil {
/**
* 按指定key排序JSONObject对象数组
*
* @param array JSONObject对象数组
* @param key 指定排序key
*/
public static void sort(JSONObject[] array, final String key) {
Arrays.sort(array, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
return JsonSortUtil.compare(a, b, key);
}
});
}
/**
* 按指定key排序JSONObject对象集合
*
* @param list JSONObject对象集合
* @param key 指定排序key
*/
public static void sort(List<JSONObject> list, final String key) {
Collections.sort(list, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject a, JSONObject b) {
return JsonSortUtil.compare(a, b, key);
}
});
}
/**
* 按指定key降序排序JSONObject对象数组
*
* @param array JSONObject对象数组
* @param key 指定排序key
*/
public static void sortDesc(JSONObject[] array, final String key) {
Arrays.sort(array, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject a, JSONObject b) {
return -1 * JsonSortUtil.compare(a, b, key);
}
});
}
/**
* 按指定key降序排序JSONObject对象集合
*
* @param list JSONObject对象集合
* @param key 指定排序key
*/
public static void sortDesc(List<JSONObject> list, final String key) {
Collections.sort(list, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject a, JSONObject b) {
return -1 * JsonSortUtil.compare(a, b, key);
}
});
}
/**
* 按指定key比较两个JSONObject对象大小
*
* @param a 第一个JSONObject对象
* @param b 第二个JSONObject对象
* @param key 指定进行比较的key
* @return
* <ul>
* <li>如果a==b,返回0</li>
* <li>如果a>b,返回1</li>
* <li>如果a<b,返回-1</li>
* </ul>
*/
public static int compare(JSONObject a, JSONObject b, String key) {
Object va = a.get(key);
Object vb = b.get(key);
if (null == va && null == vb) {
return 0;
}
if (null == va) {
return -1;
}
if (null == vb) {
return 1;
}
if (va.equals(vb)) {
return 0;
}
if (va instanceof Number && vb instanceof Number) {
/* 取double值相减,兼容整数 */
if (a.getDoubleValue(key) - b.getDoubleValue(key) > 0) {
return 1;
}
else {
return -1;
}
}
return a.getString(key).compareToIgnoreCase(b.getString(key));
}
}