Easy way to get string representation of Map <String, String []> in java?

I encoded a simple function that prints it for me, but I was wondering if there was an easier way.

I'm basically looking for something that will print keys ( Strings) and values ​​( Stringarrays), as if I were calling Arrays.toString()for values.

+5
source share
3 answers

There are two interesting methods on this site: http://www.vineetmanohar.com/2010/05/2-ways-to-convert-java-map-to-string/

The first (some code) will give you an answer in the format key = value @ key2 = value2 and ...

The second will give you XML with information

+3
source

, , , , Google Guava.

private static <K, V> Map<K, List<V>> asView(Map<K, V[]> map) {
    // returns a view of the given map so it 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);

:

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

, - , JDK.

+1

I don’t think that this is possible without encoding your own function, since the Map will always print its values ​​using its own toString () methods and for an array, which, unfortunately, is different from what Arrays.toString () produces.

You can override Map.toString () in a Map instance by copying the code from AbstractMap.toString (), and then adding special processing if that value is an array.

0
source

All Articles