简体   繁体   中英

java hashmap with List as value to property

I have a HashMap in the following format.

HashMap<String, List<String>> map

I'm trying without any luck to find the best way to write this out to a property file, is this possible? I had no problem with a HashMap<String, String> hashmap , but when the value is a List I can't figure out the best way to store this out. I Don't care if it's out in xml format or any other format, just so I can easily open the file and have it serialized or whatever back into a hashmap.

Thanks for any direction

First, you might want to consider using a ListMultimap from Guava. It implements a Map<Key, List<Value>> .

Next, I would set up an XML Schema where each element has a name and a list of values. Use JAXB to marshall the data to a file.

I'm not sure what you are currently doing, but you can always just get a set of the Map.Entry<String,List<String>> instances that compose the map and write them out any way you want. See this .

The psuedo code would look something like

for (Map.Entry<String,List<String>> entry : map.entrySet()) {
    String key = entry.getKey();
    List<String> value = entry.getValue();

    // now loop over value, which will be of type List<String>
}

A HashMap is Serializable; so you can do this by default.

FileOutputStream fileStream = new FileOutputStream("map.map");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(map);
os.close();

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