Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a HashMap with entries from a properties file

Tags:

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?

like image 889
OneMoreError Avatar asked May 02 '13 16:05

OneMoreError


People also ask

How load data from properties file?

The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties. load() method of Properties class is convenient to load . properties file in the form of key-value pairs.

How do you populate a HashMap?

To populate HashMap in previous Java versions, we have to use the put() method. You can also make a map immutable once you populate the static HashMap. If we try to modify the immutable Map, we will get java. lang.


2 Answers

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)); } 
like image 186
JB Nizet Avatar answered Sep 27 '22 23:09

JB Nizet


Use .entrySet()

for (Entry<Object, Object> entry : properties.entrySet()) {     map.put((String) entry.getKey(), (String) entry.getValue()); } 
like image 25
cahen Avatar answered Sep 27 '22 23:09

cahen