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
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())));
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));
}
Use .entrySet()
for (Entry<Object, Object> entry : properties.entrySet()) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
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;
}
you can use the below Method to load the property file in a map
public static Map<String, String> getProperties(String filePropertyFile){
Properties getProperties = new Properties();
FileInputStream inputStream = null;
HashMap<String, String> propertyMap = new HashMap<String, String>();
try {
inputStream = new FileInputStream(filePropertyFile);
getProperties.load(inputStream);
propertyMap.putAll((Map) getProperties);
} catch (Exception e) {
e.printStackTrace();
}
return propertyMap;
}
Unit Test:
@Test
public void getPropertiesTest()
String outputOmJarArrayAttributesPath = System.getProperty("user.dir") + "/src/main/resources/OutputOmJarArrayAttributes.properties";
System.out.println(PropertyFileUtils.getProperties(outputOmJarArrayAttributesPath));;
}