user2728024
user2728024

Reputation: 1546

java beginner : How key gets sorted in hashmaps?

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.

Upvotes: 3

Views: 8256

Answers (6)

csk
csk

Reputation: 576

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

Upvotes: 2

user2728160
user2728160

Reputation: 1

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

Upvotes: 0

Ashish Chaurasia
Ashish Chaurasia

Reputation: 1737

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.

Upvotes: 2

Aniket Thakur
Aniket Thakur

Reputation: 68935

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.

Upvotes: 2

newuser
newuser

Reputation: 8466

Try TreeMap,

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

use TreeMap the all keys are in sorted order

Upvotes: 0

JavaDM
JavaDM

Reputation: 851

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

Upvotes: 0

Related Questions