Populating a HashMap with entries from a properties file

Use .entrySet()

for (Entry<Object, Object> entry : properties.entrySet()) {
    map.put((String) entry.getKey(), (String) entry.getValue());
}

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));
}

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())));

Tags:

Java

Hashmap