I have hashmap and its keys are like "folder/1.txt,folder/2.txt,folder/3.txt" and value has these text files data.
Now i am stucked. I want to sort this list. But it does not let me do it :( Here is my hashmap data type:
HashMap<String, ArrayList<String>>
following function work good but it is for arraylist not for hashmap.
Collections.sort(values, Collections.reverseOrder());
I also tried MapTree but it also didn't work, or may be I couldn't make it work. I used following steps to sort the code with maptree
HashMap testMap = new HashMap();
Map sortedMap = new TreeMap(testMap);
any other way to do it??
I have one doubt as my keys are (folder/1.txt, folder/2.txt ) may be that's why?
Why not just do this?
where
ValueObject
is whatever class you're using for values.Edit: this is based on some assumptions -- waiting to get more information to see what OP really needs.
I guess that you want the list of keys sorted.
If your hashmap is called
h
, then try this:My first guess was that use use
File
objects rather thanString
objects as keys. But then I noted that you say your key is"folder/1.txt,folder/2.txt,folder/3.txt"
and your values are of typeCollection<Strings>
. If this is so, maybe your solutions should berather than
to get the single files sorted with a
TreeMap
as you tried.Use a TreeMap, and implement the Comparator interface for the folder paths.
The comparator should compare two keys according to what ever rules you want, and pass that comparator to the constructor of the TreeMap. If sorting by pure alphabetical rules are ok, then you can skip this step. If you want to do something special with the paths, then you will need to define what that is in the comparator.
Sometimes I use LinkedHashMap, when calling keySet() it gives you back items in a sorted way, as you added the to the map through put().
I believe HashMaps do not guarantee any ordering when you iterate through the keys. The iteration order depends on the buckets and collisions.
You may want to put the values into some other collection and then sort them.