Chaipau
Chaipau

Reputation: 369

How to override = symbol while converting HashMap to String using toString method?

Below is part of code where map is initialized as:
Map<Integer,Integer> map = new HashMap<>();
and the line which I want to modify the output is

System.out.println("Price and items "+map.toString());
where the output presently is
{100=10,200=5}

I want to display
{100:10,200:5}

Upvotes: 2

Views: 4993

Answers (3)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

Don't rely on the method toString() as it is an implementation detail that could change from one version of Java to another, you should rather implement your own method.

Assuming that you use Java 8, it could be:

public static <K, V> String mapToString(Map<K, V> map) {
    return map.entrySet()
        .stream()
        .map(entry -> entry.getKey() + ":" + entry.getValue())
        .collect(Collectors.joining(", ", "{", "}"));
}

If you want to have the exact same implementation as AbstractMap#toString() that checks if the key or the value is the current map, the code would then be:

public static <K, V> String mapToString(Map<K, V> map) {
    return map.entrySet()
        .stream()
        .map(
            entry -> (entry.getKey() == map ? "(this Map)" : entry.getKey())
                    + ":"
                    + (entry.getValue() == map ? "(this Map)" : entry.getValue()))
        .collect(Collectors.joining(", ", "{", "}"));
}

Upvotes: 11

Andy Turner
Andy Turner

Reputation: 140309

You can't override the symbols in the toString() method directly.

Whilst you can use String.replace for maps where the keys and values can't contain = (like Integers), you'd have to provide a different implementation in general.

You can see this isn't too tricky to do if you look at the source of AbstractMap.toString():

public String toString() {
    Iterator<Entry<K,V>> i = entrySet().iterator();
    if (! i.hasNext())
        return "{}";

    StringBuilder sb = new StringBuilder();
    sb.append('{');
    for (;;) {
        Entry<K,V> e = i.next();
        K key = e.getKey();
        V value = e.getValue();
        sb.append(key   == this ? "(this Map)" : key);
        sb.append('=');
        sb.append(value == this ? "(this Map)" : value);
        if (! i.hasNext())
            return sb.append('}').toString();
        sb.append(", ");
    }
}

You can just change the = to :.

Upvotes: 2

Since map is integer integer you can play with the toString() method and replace the undesired chars...

do string replace :)

map.toString().replace("=",":");

Upvotes: 2

Related Questions