Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to populate a HashMap using the Properties class.
I want to load the entries in the .propeties file and then copy it into the HashMap.

Earlier, I used to just initialize the HashMap with the properties file, but now I have already defined the HashMap and want to initialize it in the constructor only.

Earlier approach:

Properties properties = new Properties();

try {
    properties.load(ClassName.class.getResourceAsStream("resume.properties"));
} catch (Exception e) { 

}

HashMap<String, String> mymap= new HashMap<String, String>((Map) properties);

But now, I have this

public class ClassName {
HashMap<String,Integer> mymap = new HashMap<String, Integer>();

public ClassName(){

    Properties properties = new Properties();

    try {
      properties.load(ClassName.class.getResourceAsStream("resume.properties"));
    } catch (Exception e) {

    }
    mymap = properties;
    //The above line gives error
}
}

How do I assign the properties object to a HashMap here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
614 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understand correctly, each value in the properties is a String which represents an Integer. So the code would look like this:

for (String key : properties.stringPropertyNames()) {
    String value = properties.getProperty(key);
    mymap.put(key, Integer.valueOf(value));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...