1

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?

JavaCoder
  • 49
  • 4

2 Answers2

3

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);
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
2

Guava has a lot of useful methods. Look at Joiner.MapJoiner

Joiner.MapJoiner joiner = Joiner.on('\n').withKeyValueSeparator("=");
System.out.println(joiner.join(map));
Natalia
  • 4,362
  • 24
  • 25