Vitapen Vitapen - 2 months ago 10
Java Question

Iterate through HashMap with Class as Value

I'm trying to iterate through a HashMap where the Key is a String and Value is a Class. The trail you can see from the code eventually leads to a

toString()
which is what I want to print for each Key in the HashMap. How do I do this? Here's the code:

protected static void getAllInHash() {
for (Map.Entry<String, Class> entry : hashName.entrySet()) {
String key = entry.getKey();
Class value = entry.getValue().getClassOne().toString();
Class value2 = entry.getValue().getClassOne().getClassTwo().toString();
System.out.println(key + ": " + value + ", and: " + value2);
}
}


Many thanks.

Answer

“cannot convert from String to Class”?

Your problem is here

Class value = entry.getValue().getClassOne().toString(); // return String and not one class 

your code so quedaria for example

for (Map.Entry<String, Class> entry : hashName.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue().getClassOne().toString();
        Object value2 = entry.getValue().getClassOne().getClassTwo().toString();
        System.out.println(key + ": " + value + ", and: " + value2);
    }
Comments