[AppleScript] 纯文本查看 复制代码
/**
* @desc Map<Character, Integer> 按值排序
* @param m Map集合
* @param flag 默认为true is asc,false is desc
* @return ArrayList<Entry<Character,Integer>> ctrl+1 返回类型+返回引用名
*
* @author purity 2016-10-16下午1:51:01
*/
public static ArrayList<Entry<Character, Integer>> sortMapValueByList(Map<Character, Integer> m, final boolean flag) {
ArrayList<Entry<Character, Integer>> al = new ArrayList<Entry<Character, Integer>>(m.entrySet());
// Java.lang.IllegalArgumentException: Comparison method violates its
// general contract! jdk7的排序变了,设置以前的排序方式
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
Collections.sort(al, new Comparator<Entry<Character, Integer>>() {
@Override
public int compare(Entry<Character, Integer> lhs, Entry<Character, Integer> rhs) {
int num = lhs.getValue() - rhs.getValue();
if (flag) {
return num == 0 ? 1 : num;
} else {
return num == 0 ? 1 : -num;
}
}
});
return al;
}
/**
* @desc Map<Character, Integer> 按值排序
* @param m Map集合
* @param flag 默认为true is asc,false is desc
* @return ArrayList<Entry<Character,Integer>> ctrl+1 返回类型+返回引用名
*
* @author purity 2016-10-16下午1:51:01
*/
public static ArrayList<Map.Entry<Character, Integer>> sortMapValue(TreeMap<Character, Integer> tm,
final boolean flag) {
ArrayList<Map.Entry<Character, Integer>> al = new ArrayList<Entry<Character, Integer>>(tm.entrySet());
Collections.sort(al, new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Entry<Character, Integer> lhs, Entry<Character, Integer> rhs) {
if (flag) {
return lhs.getValue().compareTo(rhs.getValue()); // 可以直接比较
} else {
return rhs.getValue().compareTo(lhs.getValue());
}
}
});
return al;
}
/**
* @desc Map<Character, Integer> 按值排序
* @param m Map集合
* @param flag 默认为true is asc,false is desc
* @return TreeSet<Entry<Character,Integer>> ctrl+1 返回类型+返回引用名
*
* @author purity 2016-10-16下午2:12:17
*/
public static TreeSet<Entry<Character, Integer>> sortMapValueBySet(Map<Character, Integer> m, final boolean flag) {
TreeSet<Entry<Character, Integer>> ts = new TreeSet<Entry<Character, Integer>>(
new Comparator<Entry<Character, Integer>>() {
@Override
public int compare(Entry<Character, Integer> lhs, Entry<Character, Integer> rhs) {
int num = lhs.getValue() - rhs.getValue(); // 用compareTo会排除重复
if (flag) {
return num == 0 ? 1 : num;
} else {
return num == 0 ? 1 : -num;
}
}
});
ts.addAll(m.entrySet());
return ts;
}