How to sort hashmap? [closed]

2019-09-21 06:41发布

问题:

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?

回答1:

I guess that you want the list of keys sorted.

If your hashmap is called h, then try this:

SortedSet<String> sortedKeys = new TreeSet<String>(h.keySet());


回答2:

Why not just do this?

Map<String, ValueObject> testMap = new TreeMap<String, ValueObject>();

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.



回答3:

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.



回答4:

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.



回答5:

My first guess was that use use File objects rather than String 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 type Collection<Strings>. If this is so, maybe your solutions should be

map.put("folder/1.txt", ...);
map.put("folder/2.txt", ...);
map.put("folder/3.txt", ...);

rather than

map.put("folder/1.txt,folder/2.txt,folder/3.txt", new ArrayList(...));

to get the single files sorted with a TreeMap as you tried.



回答6:

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().



标签: java hashmap