填充一个HashMap与从属性文件中的条目(Populating a HashMap with en

2019-09-01 18:48发布

我想填充一个HashMap使用Properties类。
我要加载的项.propeties文件,然后将其复制到HashMap

此前,我以前只是初始化HashMap与属性文件,但现在我已经定义了HashMap ,并希望仅在构造函数中进行初始化。

此前的做法:

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

但现在,我有这个

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

如何分配对象的属性的HashMap吗?

Answer 1:

如果正确地明白,在属性的每个值是代表一个整数的字符串。 因此,代码是这样的:

for (String key : properties.stringPropertyNames()) {
    String value = properties.getProperty(key);
    mymap.put(key, Integer.valueOf(value));
}


Answer 2:

使用.entrySet()

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


Answer 3:

Java的8风格:

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


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


文章来源: Populating a HashMap with entries from a properties file
标签: java hashmap