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?
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.
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.
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)); }
Use .entrySet()
for (Entry<Object, Object> entry : properties.entrySet()) { map.put((String) entry.getKey(), (String) entry.getValue()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With