Подтвердить что ты не робот

Заполнение HashMap записями из файла свойств

Я хочу заполнить 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 здесь?

4b9b3361

Ответ 1

Если я правильно понимаю, каждое значение в свойствах является строкой, представляющей целое число. Таким образом, код будет выглядеть так:

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

Ответ 2

Используйте .entrySet()

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

Ответ 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())));

Ответ 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;
    }