I have a HashMap to which I am adding integers from an array. The key is the integer and the value is the number of duplicates of the integer. When I iterate through the HashMap to get the keys in the HashMap they seem to be in random order. Is there any particular order in which these keys are added ? This is how I am iterating through.
Set<String> a = names.keySet();
Iterator i = a.iterator();
while(i.hasNext())
String t = (String) i.next();
Indeed,
HashMapreturns entries in a nondeterministic (unpredictable/unreliable) order. If you want entries to appear in order by key (so,2before3), use aTreeMap(javadoc). If you want entries to appear in order by initial insertion, use aLinkedHashMap(javadoc).Edited to add: You say that “the key is the integer”, but then you use
Stringeverywhere. Note that the string"123"sorts before the string"23", just as"abc"would sort before"bc". If you want your keys treated as numbers, e.g. by being sorted in numeric order, then you should be using a numeric type, such asInteger, rather thanString. (It’s technically possible to give yourTreeMapaComparator<String>that compares string-valued keys by examining their contents and doing an integer comparison, but I don’t think you want to do that.)