Populating a HashMap with entries from a properties file
72,702
Solution 1
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));
}
Solution 2
Use .entrySet()
for (Entry<Object, Object> entry : properties.entrySet()) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
Solution 3
Java 8 Style:
Properties properties = new Properties();
// add some properties here
Map<String, String> map = new HashMap();
map.putAll(properties.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().toString(),
e -> e.getValue().toString())));
Solution 4
public static Map<String,String> getProperty()
{
Properties prop = new Properties();
Map<String,String>map = new HashMap<String,String>();
try
{
FileInputStream inputStream = new FileInputStream(Constants.PROPERTIESPATH);
prop.load(inputStream);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Some issue finding or loading file....!!! " + e.getMessage());
}
for (final Entry<Object, Object> entry : prop.entrySet()) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
return map;
}
![OneMoreError](https://i.stack.imgur.com/G2Q2W.jpg?s=256&g=1)
Comments
-
OneMoreError almost 2 years
I want to populate a
HashMap
using theProperties
class.
I want to load the entries in the.propeties
file and then copy it into theHashMap
.Earlier, I used to just initialize the
HashMap
with the properties file, but now I have already defined theHashMap
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?