Computer Hope
Software => Computer programming => Topic started by: Tokkulmann 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.
-
I couldn't get your example to compile.
but here is mine. seems to work fine:
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());
}
}
}
-
Oh, I seems like casting me.getKey to a string did the trick, like you did in your code.
Thanks.