We help IT Professionals succeed at work.

Displaying contents of ConcurrentHashMap

ambuli
ambuli asked
on
Hi Experts,

 In the following code snippet, I am trying to print the values in the map.  How can I
properly iterate through the map.

Thanks
ConcurrentMap m_RequestQueue = new ConcurrentHashMap< String, QueueData>();
...
...
...  
 
 
public void displayQueues()
    {
        System.out.println("Request Queue:");
        Iterator it = m_RequestQueue.keySet().iterator();
       
        while (it.hasNext())
        {          
            QueueData reqData = (QueueData) it.next();  // cast exception
            reqData.printData();
        }
    }

Open in new window

Comment
Watch Question

Analyst Programmer
Commented:
Your key is of String type. You should solve in either way in the following code:


        System.out.println("Request Queue:");
 
        // Solution 1:
        Iterator it = m_RequestQueue.keySet().iterator();
        while (it.hasNext())
        {          
            QueueData reqData = (QueueData)m_RequestQueue.get(it.next());
            reqData.printData();
        }
 
        // Solution 2:
        Iterator it = m_RequestQueue.values().iterator();
        while (it.hasNext())
        {          
            QueueData reqData = (QueueData) it.next();  // cast exception
            reqData.printData();
        }

Open in new window

You can use this,
 
Map<String,String> map = new ConcurrentHashMap<String,String>();
for(Entry<String, String> entry: map.entrySet()) {
   String key = entry.getKey();
   String value = entry.getValue();
}

Explore More ContentExplore courses, solutions, and other research materials related to this topic.