1

I want to write a program that prints out entries "0" and "4" of the HashMap (i.e. entry.getKey(0) and entry.getKey(4) but it won't let me do this) What would be another way using what I already have?

Basically I have this:

HashMap<String, Integer> hm = new HashMap<String, Integer>();

I can iterate over each entry using this code:

for (Map.Entry<String,Integer> entry : hm.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

Since people have asked for more contextual information, I am storing a set of strings in the HashMap. For example the 0th entry is "Bob", the 1st entry is "Mindy", the 2nd is "Yasser", the 3rd is "Greg" and the 4th is "Jacky." I want the program to print out the 0th and 4th entries of the populated HashMap.

8
  • 1
    Use hm.get("0") and hm.get("4")? Commented May 12, 2013 at 6:09
  • @sanbhat: I am getting the item by key. There is no concept of index in Map or Set anyway. Commented May 12, 2013 at 6:12
  • @ nhahtdh: while I thank you for the suggestion, all I get is a boolean response (i.e. null) when I want it to return a string Commented May 12, 2013 at 6:16
  • @LorraineJane: So you want the reversed mapping? i.e. Your current Map is String --> Integer, and you want to find reversed mapping of Integer --> String? Commented May 12, 2013 at 6:19
  • @LorraineJane when you store something to the HashMap, the insertion order is not maintained. U need to use LinkedHashMap for such purpose which maintains the insertion order, and makes retrieval of 1st or 4th entry easy. Commented May 12, 2013 at 6:26

6 Answers 6

3

If you are specific about the keys in the Map, you can directly use get() method.Like this,

Integer value = hm.get("0");

If you want to iterate then use something like the code below :

HashMap<String, Integer> hm = new HashMap<String, Integer>();
for (Entry<String, Integer> entry : hm.entrySet())
{
    String key = entry.getKey();
    if(key.equals("0") || key.equals("1"))
    System.out.println(key + "/" + entry.getValue());
}

You cannot pass index to the getKey() method like getKey(0) etc. Refer the documentation.

HashMap 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. So, if you are looking to fetch values from a HashMap based on index, probably it is not possible. Closest to your requirement will be something like LinkedHashMap, which maintains the order of keys for insertion/access order.

HashMap works on principle of hashing, we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap. When we pass Key and Value object to put() method on Java HashMap, HashMap implementation calls hashCode() method on Key object and applies returned hashcode() into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic.

Sign up to request clarification or add additional context in comments.

9 Comments

Why would you iterate the whole map just to get value of 2 keys?
There is no point in iterating the map either. Just show the correct way.
I want to write a program that iterates over the entries of a HashMap It would appear, @nhahtdh that this is what OP wants..
@nhahtdh We don't know the context this program is being used in. Perhaps the other entries are being used as part of a calculation. Regardless of your speculation on the subject, this seems to be the closest to a correct answer.
@LorraineJane I think you've confused half of us here. Re-phrase your question so we can all get on the same page please :)
|
2

The HashMap has no defined ordering of keys. You may use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet(). And then you pick the 0th or 4th key.Later you can retrieve the value for the keys you fetched at 0th and 4th location.

2 Comments

I think the key is the string "0", not the position
@Bohemian: I think OP explained that 0 and 4 are the ordering (assumed to be index) of some entry inside the HashMap. LinkedHashMap is the closest that offers access by index.
1

I would recommend simply using the get() method with the provided key. Iteration is not necessary in this case.

1 Comment

HashMap uses a key, not an index. Please be more specific for future readers :)
0

Since people have asked for more contextual information, I am storing a set of strings in the HashMap. For example the 0th entry is "Bob", the 1st entry is "Mindy", the 2nd is "Yasser", the 3rd is "Greg" and the 4th is "Jacky." I want the program to print out the 0th and 4th entries of the populated HashMap.

With how it is being used, an HashMap makes no sense. Use a String[] instead!

    String[] names = {"Bob", "Mindy", "Yasser", "Greg", "Jacky" };
    System.out.println("When " + names[0] + " met " + names[4]);

Comments

0

Why not a targeted approach:

String[] targets = {"0", "4"};
for (String target : targets) {
    System.out.println(target + "/" + hm.get(target));
}

Way more efficient than the "big hammer" full iteration approach, and you get output order for free.

Comments

0

If you have a lot of entries in your Map you may considerate to use one of the navigable collections, like TreeMap.

    NavigableMap<String,String> map = new TreeMap<>()
    map.subMap("0", true, "4", true);

Visit: http://docs.oracle.com/javase/6/docs/api/java/util/NavigableMap.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.