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;
    }
Share:
72,702
OneMoreError
Author by

OneMoreError

A GEEK WANNABE

Updated on July 24, 2022

Comments

  • OneMoreError
    OneMoreError almost 2 years

    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?