[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 661
  • Last Modified:

Displaying contents of ConcurrentHashMap

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

0
ambuli
Asked:
ambuli
1 Solution
 
Peter KwanCommented:
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

0
 
Ajay-SinghCommented:
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();
}
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now