Search code examples
javadictionarypretty-print

How to modify Map's output style?


I have a method like this:

public static void main(String[] args) {
        Map<String, Long> var = Files.walk(Paths.get("text"), number)
                .filter(path -> !Files.isDirectory(path))
                    .map(Path::getFileName)
                    .map(Object::toString)
                    .filter(fileName -> fileName.contains("."))
                    .map(fileName -> fileName.substring(fileName.lastIndexOf(".") + 1))
                    .collect(Collectors.groupingBy(
                                    extension -> extension,
                                    Collectors.counting()
                            )
                    );
        System.out.println(var);
}

As we know, output will be like:

{text=1, text=2}

Is it possible to change the output to:

text = 1
text = 2

I want to have some more freedom, e. g. remove brackets and commas, add new lines after number etc.


Solution

  • You can iterate over the results of the map, and just print them out:

    for (Map.Entry<String, Long> entry : var.entrySet())
    {
        System.out.println(entry.getKey() + " = " + entry.getValue());
    }
    

    Then if you want more control, you can just modify how the line gets printed, since you have the raw key and value objects.