Search code examples
javatreemaps

Java: Replace in TreeMap


I have a Treemap:

TreeMap<String, Integer> map = new TreeMap<String, Integer>();

It counts words that are put in, for example if I insert:

"Hi hello hi"

It prints:

{Hi=2, Hello=1}

I want to replace that "," with a "\n", but I did not understand the methods in Java library. Is this possible to do? And is it possible to convert the whole TreeMap to a String?


Solution

  • When printing the map to the System.out is uses the map's toString function to print the map to the console.

    You could either string replace the comma with a newline like this:

    String stringRepresentation = map.toString().replace(", ", "\n");
    

    This might however poses problems when your key in the map contains commas.

    Or you could create a function to produce the desired string format:

    public String mapToMyString(Map<String, Integer> map) {
        StringBuilder builder = new StringBuilder("{");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            builder.append(entry.getKey()).append('=').append(entry.getValue()).append('\n');
        }
        builder.append('}');
        return builder.toString();
    }
    
    String stringRepresentation = mapToMyString(map);