使用属性文件中的条目填充HashMap

我想使用Properties类填充HashMap
我想加载.propeties文件中的条目,然后将其复制到HashMap

之前,我曾经使用属性文件初始化HashMap ,但现在我已经定义了HashMap并且只想在构造函数中初始化它。

早期方法:

 Properties properties = new Properties(); try { properties.load(ClassName.class.getResourceAsStream("resume.properties")); } catch (Exception e) { } HashMap mymap= new HashMap((Map) properties); 

但现在,我有这个

 public class ClassName { HashMap mymap = new HashMap(); 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

如果我理解正确,属性中的每个值都是一个表示整数的String。 所以代码看起来像这样:

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

使用.entrySet()

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

Java 8风格:

 Properties properties = new Properties(); // add some properties here Map map = new HashMap(); map.putAll(properties.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()))); 
 public static Map getProperty() { Properties prop = new Properties(); Mapmap = new HashMap(); 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 entry : prop.entrySet()) { map.put((String) entry.getKey(), (String) entry.getValue()); } return map; }