1

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

4
  • Properties are strings. Concat the List to comma separated. e.g. value1,value2,value3,value4 and add it to your Properties object. Commented Oct 10, 2011 at 20:31
  • 1
    @BrianRoach that would assume that the values Strings do not contain commas. Commented Oct 10, 2011 at 21:23
  • @John - Well, yes. And if they did you could quote the values, use pipe instead of comma, etc ... not rocket science :) Commented Oct 10, 2011 at 21:44
  • @BrianRoach Don't say that! I might not paid as much! ;) Commented Oct 10, 2011 at 21:58

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>
}

Comments

0

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();

1 Comment

This is what I was hoping to do, my value that is a List is a subList and that is causing a problem, but not sure the best way around it yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.