Search code examples
javaandroidsortingsharedpreferencestreemap

Sort TreeMap based on own rule


I've a TreeMap and I want to sort the keys based on my own rule. This is how I get the keys:

SharedPreferences pref = context.getSharedPreferences("myPrefs2",
                    MODE_PRIVATE);
TreeMap<String, ?> keys = new TreeMap<String, Object>(pref.getAll());

As you can see I get the keys from SharedPreferences. The keys come in the following order: Yesterday, Older, Today.

I want the following order from Today to Older. So: Today, Yesterday, Older.

I've tried something like this:

SharedPreferences pref = context.getSharedPreferences("myPrefs2",
                MODE_PRIVATE);
TreeMap<String, ?> keys = new TreeMap<String, Object>(pref.getAll()) {
    public int compare(String o1, String o2) {
        // Here the return based on our own rule
    }
};

But I don't know how to define that rule and I'm not sure if I correctly use the compare function.

Is is possible to sort the TreeMap on the rule as I described above?


Solution

  • Yes, it's absolutely possible to do what you're describing, but you need a Comparator, instead of overriding anything in TreeMap

    Comparator<String> sortByPreferenceKey = new Comparator<String>(){
        public int compare(String o1, String o2) {
            // Put your comparison logic here
        }
    };
    SharedPreferences pref = context.getSharedPreferences("myPrefs2", MODE_PRIVATE);
    TreeMap<String, Object> keys = new TreeMap<String, Object>(sortByPreferenceKey);
    keys.putAll(pref.getAll());