简体   繁体   中英

Converting a Java Map object to a Properties object

Is anyone able to provide me with a better way than the below for converting a Java Map object to a Properties object?

    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put("key", "value");

    Properties properties = new Properties();

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

Thanks

Use Properties::putAll(Map<String,String>) method:

Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");

Properties properties = new Properties();
properties.putAll(map);

you also can use apache commons-collection4

org.apache.commons.collections4.MapUtils#toProperties(Map<K, V>)

example:

Map<String, String> map = new LinkedHashMap<String, String>();

map.put("name", "feilong");
map.put("age", "18");
map.put("country", "china");

Properties properties = org.apache.commons.collections4.MapUtils.toProperties(map);

see javadoc

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MapUtils.html#toProperties(java.util.Map)

You can do this with Commons Configuration:

Properties props = ConfigurationConverter.getProperties(new MapConfiguration(map));

http://commons.apache.org/configuration

Try MapAsProperties from Cactoos :

import org.cactoos.list.MapAsProperties;
import org.cactoos.list.MapEntry;
Properties pros = new MapAsProperties(
  new MapEntry<>("foo", "hello, world!")
  new MapEntry<>("bar", "bye, bye!")
);

Simple use putAll()

Properties pro = new Properties();
pro.putAll(myMapObject);

As it accepts Map as input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM