3

i am new to java and was learning the concepts of hashmaps.

I am confused how the keys are sorted in hashmaps. i understood that its based on string length. but i am confused how data is sorted when the string length is same.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExample
{

    public static void main(String args[])
    {
        Map<String,String> map = new HashMap<String,String>(20);//SPECIFYING THE TYPE FOR FINDING HASH CODES.


        //Adding values to the HashMap
        map.put("key value a", "test value 1");
        map.put("key value b", "test value 2");
        map.put("key value c", "test value 3");

        System.out.println("Retrieving values from HashMap");
        retrieveValuesFromListMethod(map);
        System.out.println("**********************");


    }

    /*This method retrieves values from Map
     */
    public static void retrieveValuesFromListMethod(Map map)
    {
        Set keys = map.keySet();
        Iterator itr = keys.iterator();

        String key;
        String value;

        while(itr.hasNext())
        {
            key = (String)itr.next();
            value = (String)map.get(key);
            System.out.println(key + " - "+ value); 
        }
    }
}

this is my code.

output is

Retrieving values from HashMap
key value c- test value 3
key value b- test value 2
key value a- test value 1
**********************

but instead of a,b,c if i give aa,ab,ac the output is different

Retrieving values from HashMap
key value ab - test value 2
key value aa - test value 1
key value ac - test value 3
**********************

for 1,2,3

Retrieving values from HashMap
key value 1 - test value 1
key value 2 - test value 2
key value 3 - test value 3
**********************

how sorting is done in hashmap? Please help!!

Thanks in advance.

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
user2728024
  • 1,496
  • 8
  • 23
  • 39
  • What do you mean sorting? A hash map is not sorted and has no natural structure for iteration. – Kon Aug 29 '13 at 06:56
  • Hashmap is not sorted. You may check this for some more details http://stackoverflow.com/a/2889800/869488 – rajesh Aug 29 '13 at 06:56
  • 1
    Read the docs about Map and HashMap. – Maroun Aug 29 '13 at 06:57
  • well, how about using a treemap instead? treeMaps keeps things sorted by key.( As long as the class have a comparison method, wich string naturally has) – DeH Aug 29 '13 at 06:58

6 Answers6

2
java beginner : How key gets sorted in hashmaps?

Taking from answer from here which is also the answer to your question

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<String, Float>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.

If you want to preserve the order in which the data was inserted into the map you can use LinkedHashMap.

Community
  • 1
  • 1
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
2

java.util.HashMap is unordered; you can't and shouldn't assume anything beyond that.

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

java.util.LinkedHashMap uses insertion-order.

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

java.util.TreeMap, a SortedMap, uses either natural or custom ordering of the keys.

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

Ashish Chaurasia
  • 1,747
  • 17
  • 23
2

In your case , when you are using the following

//Adding values to the HashMap
    map.put("key value a", "test value 1");
    map.put("key value b", "test value 2");
    map.put("key value c", "test value 3");

here is the snap of hashmap after the insertion of the keys

Data in Hashmap after insertion of key value

HashMap internally uses Array of Entry Map , hashcode generated by the keys are input to the hashing function that makes this key to be inserted in the array in the order you are looking into it . You are using iterator to iterate the hashmap ,have a look at the snap of iterator for the above collection, since the iterator is looking at the collection in the following order , it just seems the keys are sorted but are actually not . Iterator snap for iterating over the above hashmap (Note : Iterator doesn't guarantee for the iteration in the order in which the elements are present in collection ) so its just a resemblance not the actual behavior of hashmap . This behavior for sorted key is given by TreeMap or any collection implementing interface SortedMap and the key when comparable .

I hope above information will be helpful to you

csk
  • 566
  • 1
  • 5
  • 15
0

A Hashmap is not sorted. If you have to keep the order, you have to use e.g. LinkedHashMap<K, V>

JavaDM
  • 851
  • 1
  • 6
  • 29
0

Try TreeMap,

Map<String, String> sampleMap = new TreeMap<String, String>(map);

use TreeMap the all keys are in sorted order

newuser
  • 8,338
  • 2
  • 25
  • 33
0

hashmap is not sorted, the output is different because the String's hashcode is not same.