Reputation: 3496
I'm having a weird problem with HashMap in Android. I'm putting values into the hashmap which is of the form
HashMap <String,String> sample = new HashMap<String,String>();
However let's say I'm putting the following values in the following order:
sample.put("ifi1", "video1");
sample.put("ifi2", "video2");
sample.put("ifi3", "video3");
sample.put("ifi4", "video4");
sample.put("ifi5", "video5");
sample.put("ifi6", "video6");
sample.put("ifi7", "video7");
sample.put("ifi8", "video8");
sample.put("ifi9", "video9");
This is just a simple example that is similar to what i have. I only have a bigger list in my actual code. However when I now try to print only the values, I get an unordered list as follows:
VIDEOS: video1
VIDEOS: video3
VIDEOS: video2
VIDEOS: video5
VIDEOS: video4
VIDEOS: video7
VIDEOS: video6
VIDEOS: video9
VIDEOS: video8
where in fact I'm expecting it to produces the following list:
VIDEOS: video1
VIDEOS: video2
VIDEOS: video3
VIDEOS: video4
VIDEOS: video5
VIDEOS: video6
VIDEOS: video7
VIDEOS: video8
VIDEOS: video9
Why is this, any idea?
Upvotes: 10
Views: 22514
Reputation: 420951
That's right. The HashMap
implementation of Map
does not guarantee any order during iteration.
...have a look at LinkedHashMap
:
Map<String, String> sample = new LinkedHashMap<String, String>();
sample.put("ifi1", "video1");
sample.put("ifi2", "video2");
sample.put("ifi3", "video3");
sample.put("ifi4", "video4");
sample.put("ifi5", "video5");
sample.put("ifi6", "video6");
sample.put("ifi7", "video7");
sample.put("ifi8", "video8");
sample.put("ifi9", "video9");
for (String video : sample.values())
System.out.println(video);
// Prints
video1
video2
video3
video4
video5
video6
video7
video8
video9
Use a NavigableMap
or SortedMap
implementation such as a TreeMap
.
Upvotes: 33
Reputation: 4754
If you use Simple HashMap then this class use some hashing technique to store the value ,at the time of extracting the data from list its use same hash technique. And Hash function are not ordered. that's why result is coming unordered. In Placed of HashMap you have to use LinkedHashMap to make it ordered List.
Upvotes: 0
Reputation: 6335
In HashMap order is not there. Try using LinkedHashMap instead. LinkedHashMap
keeps track of the keys based on insertion order, so that when you do a call to getKeySet()
, you will get the keys back in the order you put them in.
Upvotes: 4
Reputation: 13792
look for a class that implements SortedMap interface. Or for print purposes only, you can order de Set returned from your Map with Collections.sort
Upvotes: 0
Reputation: 27880
You can also use a LinkedHashMap
in order to obtain the collection of entries in the same order they were inserted in.
Upvotes: 0
Reputation: 3519
You need to use SortedMap
instead of HashMap
. It will guarantee order.
Upvotes: 5