Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: [Java]Using a map key as a string  (Read 6570 times)

0 Members and 1 Guest are viewing this topic.

Tokkulmann

    Topic Starter


    Rookie

    • Yes
  • Experience: Familiar
  • OS: Windows 7
[Java]Using a map key as a string
« on: October 09, 2011, 04:06:14 PM »
In Java, is there any way to use a map key as a string to manipulate?

Say I was storing:

Key:Jennifer
Value:123456789

in a map, is there anyway I could access the key "Jennifer" as a string?

As it stands, I have a hashmap that stores (string, int) key/value pairs and I wish to access the key for use as a string.

Here's an example of something I'm trying:

Set set = map.entrySet();
Iterator i = set.iterator();

while (i.hasNext()){
    Map.Entry me = (Map.Entry)i.next();
    System.out.print (me.getKey().length());
}

This doesn't seem to work.

Right now, I'm creating a set from my HashMap using .entrySet() and then using an iterator, I'm creating map entries from the map and extracting keys using get.key().

However, it doesn't seem like it allows me to perform typical string functions on it like .length() or .substring(x,y)

I appreciate any insight into this.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: [Java]Using a map key as a string
« Reply #1 on: October 09, 2011, 04:20:45 PM »
I couldn't get your example to compile.

but here is mine. seems to work fine:


Code: [Select]
import java.util.*;
public class testmap {
    public static void main(String[] args) {
      HashMap<String,Integer> testmap=new HashMap<String,Integer>();
     
     
      testmap.put("Billy", 500);
      testmap.put("Jerry",400);
      testmap.put("Lisa", 40);
      testmap.put("Jennifer", 80);
     
      Set<Entry<String, Integer>> grabset = testmap.entrySet();
      Iterator<Map.Entry<String,Integer>> i = grabset.iterator();

      while (i.hasNext()){
          Map.Entry<String,Integer> me = (Map.Entry<String,Integer>)i.next();
          System.out.println (((String)me.getKey()).length());
      }
     
     
     
     
    }
       
}

I was trying to dereference Null Pointers before it was cool.

Tokkulmann

    Topic Starter


    Rookie

    • Yes
  • Experience: Familiar
  • OS: Windows 7
Re: [Java]Using a map key as a string
« Reply #2 on: October 09, 2011, 06:25:06 PM »
Oh, I seems like casting me.getKey to a string did the trick, like you did in your code.

Thanks.