How to modify Map's output style?

84 Views Asked by At

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.

2

There are 2 best solutions below

4
On BEST ANSWER

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.

2
On

What about something as simple as:

map.toString().replace(", ", "\n");