I created a hashmap where I store directories as keys and then their contents as values.
When I iterate over the hash map and print everything out I get
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/ek.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/nu.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/os.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/di.html
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/po.html
What I want to get however is
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/di.html
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/po.html
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/ek.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/nu.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/os.java
Any ideas?
To come to this I am sorting the hashmaps keys and then print the values of each key
A HashMap is not usually sorted. You will want to use a SortedMap, for example TreeMap. This class will let you use your own Comparator, and thus lets you sort its contents anyway you want it. From the TreeMap(Comparator<? super K>) constructor Javadoc:
Constructs a new, empty tree map, ordered according to the given comparator.
Try using a TreeMap with a suitable Comparator, then putAll entries you have in your HashMap.
If you need to start with a HashMap, you can create a new TreeMap(myHashMap). This will have the same mappings, but will iterate over them in sorted order.
Related
I need to sort a hash map according to the key.The key is a string(so I need to sort it alphabetically) and the value is an integer.
I was trying to search online and found that tree set automatically sorts it once you put it. Could somebody guide me in the right direction as to how I could convert it into a tree set or maybe even if i could just sort it using a hash map.
Thanks in advance
Since hashmaps are unsorted maps by definition you'd need to use another container for that. Depending on your needs there are several options, some being:
Use a TreeMap instead of a HashMap either temporarily or as a replacement. This would be the best option unless you have to keep the hashmap.
Use a TreeSet to sort the keys, then iterate over the keys and extract the values from the HashMap.
Do the same as in option 2 but fill a new LinkedHashMap during iteration. This will result in a map that returns the values in insert order which happens to be sort order due to use of a sorted set. Note that adding elements to the LinkedHashMap will append any new elements to the end - LinkedHashMap is still ordered by insertion order.
I am trying to get values from an ArrayList that is sorted and want to store it in a HashMap, where the values of the ArrayList become keys of the HashMap. Will the order of the values in the HashMap still be the same as that of ArrayList?
No. Use a TreeMap instead. This will preserve the order of insertion.
HashMap makes no guarantees as to the order the mappings are stored or iterated, so simply running through the ArrayList and putting them into the HashMap as keys will very likely result in unordered iterations.
As others have pointed out, LinkedHashMap does preserve insertion order for iterations. An additional run of insertions will result in unordered iterations again, though. Both HashMap and LinkedHashMap support constant time lookup - LinkedHashMap pays for its extra feature in space (by maintaining pointers between the keys).
As others have also pointed out, TreeMap preserves order after updates, so this might be a better option for you, or not. Of course, if the ArrayList is sorted with a specific Comparator, you must feed that same Comparator to the TreeMap on construction for the sorting to be the same. Note that TreeMap does not have constant time lookup, due to being implemented as a Red-Black search tree.
As your ArrayList has been ordered, no need to use a TreeMap because this will compare to order again and it's not necessary. You should use a LinkedHashMap that will keep the exact order of your ArrayList when you put your value in.
Check This: Insert Values of ArrayList into HashMap
HashMap<String, Item> itemMap = new HashMap<String, Item>();
for (Item item : itemList)
{
itemMap.put(item.getitemCode(), item);
}
I have situation where there is a HashMap as
Map<Integer,ArrayList> key = new HashMap<Integer,ArrayList>();
The array list has [rankOfCard,suitOfCard]
I want to sort this Map in such a way that If the value is
(1,[3,1])
(2,[2,4])
(3,[1,3])
(4,[1,2])
(5,[2,3])
Output should be :
(4,[1,2])
(3,[1,3])
(5,[2,3])
(2,[2,4])
(1,[3,1])
How can I achieve this ?
Iterate through entry set and Collection.sort(entry.value())
A Map is not sorted, so it's not the right data structure for your task.
A SortedMap sorts on keys, so it's no good as well, since you want your map sorted by value.
Your question does not clarify what the key of the Map is, but maybe you could use a custom class in a regular List, and have the class implement the Comparable interface, or implement an external Comparator, to sort the List.
I'm looking for a way to maintain the sorting on my key-value pairs. They are sorted by variables outside of the actual key-value pairs (for better UI). I am currently using a Hashtable, but that does not maintain the sorting =(
Hashtable<Integer, String> subscriptions = getUsersSubscriptions(user);
Is there some simple way that Java lets one store pairs? The best idea I can think of is using 2 associated ArrayLists (one of type Integer, another of type String). Can someone think of something better?
If your key-value pairs are already sorted, LinkedHashMap will maintain order of insertion.
In other words, the keys returned by map.keySet() will be in the exact order you put them into the map.
SortedMap<Integer, String> myMap = new TreeMap<Integer,String>();
If you have a custom sorting, pass a Comparator instance to the constructor of the TreeMap. But be careful doing so, as using a Comparator that does not go well with natural Integer order would make things impossible to understand and debug.
LinkedHashMap can be used here.
Is there some simple way that Java lets one store pairs?
Create a custom class that stores the two properties.
They are sorted by variables outside of the actual key-value pairs
Add a third property for the sort data.
Then your class can implement Comparable to sort the data as required based on this property.
Or you can use a custom Comparator to sort on the sort data field.
Now the class instances can be stored in an ArrayList.
I have one Map that contains some names and numbers
Map<String,Integer> abc = new HashMap<String,Integer>();
It works fine. I can put some values in it but when I call it in different class it gives me wrong order. For example:
I putted
abc.put("a",1);
abc.put("b",5);
abc.put("c",3);
Iterator<String> iter = abc.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
System.out.println(name);
}
some time it returns the order (b,a,c) and some time (a,c,b).
What is wrong with it? Is there any step that I am missing when I call this map?
Edit:
I changed to HashMap and result is still same
The only thing that's wrong is your expectations. The Map interface makes no guarantees about iteration order, and the HashMap implementation is based on hash functions which means the iteration order is basically random, and will sometimes change completely when new elements are added.
If you want a specific iteration order, you have thee options:
The SortedMap interfaces with its TreeMap implementation - these guarantee an iteration order according to the natural ordering of the keys (or an ordering imposed by a Comparator instance)
The LinkedHashMap class iterates in the order the elements were added to the map.
Use a List instead of a Map - this has a well-defined iteration order that you can influence in detail.
I think you need LinkedHashMap.
A TreeMap will always have keys in their natural order (unless you provide a comparator) If you are seeing the order any differently it will be the way you are looking at the map and what you are doing with it. If in doubt, use a debugger and you will see the order is sorted.
If you wish to get map values in the same order you used to insert them use LinkedHashMap instead.