Easy way to get a string representation of Map<String, String[]> in java?
I've coded a simple function that prints it for me but I was wondering if ther开发者_Go百科e was an easier way.
I'm basically looking for something that will print the keys (String
s) and the values (String
arrays), as if I invoked Arrays.toString()
on the values.
this site have two interesting methods: http://www.vineetmanohar.com/2010/05/2-ways-to-convert-java-map-to-string/
The first one (some code) will give you an answer in the format key=value @ key2 = value2 & ...
The second one will give you a XML with the information
An old question, but maybe useful for someone who use core libs only like Google Guava.
private static <K, V> Map<K, List<V>> asView(Map<K, V[]> map) {
// returns a view of the given map so it's considered cheap during construction
// may be expensive on multiple re-iterations
return transformEntries(map, new EntryTransformer<K, V[], List<V>>() {
@Override
public List<V> transformEntry(K key, V[] value) {
return asList(value);
}
});
// java 8: return transformEntries(map, (k, v) -> asList(v));
}
...
final Map<String, String[]> map = ImmutableMap.of(
"one", new String[] {"a", "b", "c"},
"two", new String[] {"d", "e", "f"},
"three",new String[] {"g", "h", "i"}
);
final Map<String, List<String>> view = asView(map);
System.out.println(map);
System.out.println(view);
Sample output:
{one=[Ljava.lang.String;@4a4e79f1, two=[Ljava.lang.String;@6627e353, three=[Ljava.lang.String;@44bd928a}
{one=[a, b, c], two=[d, e, f], three=[g, h, i]}
Note that the output is JDK-defined default formatted output.
I don't think this is possible without coding your own function, since the Map will always print its values using their own toString() methods, and for an array, that's unfortunately different from what Arrays.toString() produces.
You might override Map.toString() in your Map instance, by copying the code from AbstractMap.toString(), and then adding the special handling if the value is an array.
精彩评论