HashMap Keys and Values

Posted on 2006-04-06
Last Modified: 2012-06-21
I'm trying to get the keys with corresponding values out of a HashMap.  It's easy to get the values, but how do I get the corresponding key?

Here's my code -- assume the hashmap has been filled.

HashMap hm;

Iterator it = hm.values().iterator();
while (it.hasNext()) {

    String value = (String);
Question by:lcor
    LVL 86

    Accepted Solution

    Iterator it = hm.entrySet().iterator();
    while (it.hasNext()) {
        Entry e = (Entry);
        String key = e.getKey().toString();
        String value = e.getValue().toString();
    LVL 92

    Assisted Solution

    iterate on the key:

    Iterator it = hm.keySet().iterator();
    while (it.hasNext()) {

        String key = (String);
        String value = (String) hm.get(key);
    LVL 86

    Expert Comment


    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    matchUp  challenge 9 51
    Fibonacci challenge 11 61
    groovy example issue 10 33
    JAVA part two 4 10
    By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
    Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
    Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
    The viewer will learn how to implement Singleton Design Pattern in Java.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now