使用TreeMap对SharedPreferences进行排序 - 未正确排序

时间:2014-06-11 14:11:06

标签: java android sorting sharedpreferences treemap

所以我需要对SharedPreferences进行排序,其中包含Float数字。

所以我用;

添加数据
SharedPreferences.Editor editor = getSharedPreferences(
            "Huskr_headline", 0).edit();
            editor.putFloat(tilfoejopgave_headline.getText().toString(), Float.valueOf(tilfoejopgave_klokken.getText().toString()));
            editor.commit();

获取数据;

SharedPreferences Huskr_headline = getSharedPreferences(
            "Huskr_headline", 0);

TreeMap<String, ?> Huskr_headline_treemap = new TreeMap<String, Object>(
            Huskr_headline.getAll());

for (Map.Entry<String, ?> entry : Huskr_headline_treemap.entrySet()) {

}

以值输出;

10,12,14,17,8,81,9

反过来我希望它输出值;

8,9,10,12,14,17,81

如何让它做到这一点?键是随机的字符串..我想我需要按值排序,但如何做到这一点?

由于

2 个答案:

答案 0 :(得分:2)

TreeMap提供自定义Comparator,然后根据您的需要对其中的条目进行排序。

答案 1 :(得分:0)

OP解决方案。

找到答案

用过这个         private static Map sortByComparator(Map unsortMap){

    List list = new LinkedList(unsortMap.entrySet());

    // sort list based on comparator
    Collections.sort(list, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue())
                    .compareTo(((Map.Entry) (o2)).getValue());
        }
    });

    // put sorted list into map again
    // LinkedHashMap make sure order in which keys were inserted
    Map sortedMap = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
}

有了这个;

    SharedPreferences Huskr_headline_conn = getSharedPreferences(
            "Huskr_headline", 0);
    Map<String, ?> Huskr_headline = Huskr_headline_conn.getAll();


    Map<String, String> sortedMap = sortByComparator(Huskr_headline);

    for (Map.Entry entry : sortedMap.entrySet()) {
 }

http://www.mkyong.com/java/how-to-sort-a-map-in-java/

上的功能