1

I couldn't find the answer to my question so I am hoping you can help me.

Is there a way to print this without the comma at the end?

for (Map.Entry<String, String> entry : words.entrySet()) {
    System.out.printf("%s <=> %s, ", entry.getKey(), entry.getValue());
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
user14583977
  • 73
  • 1
  • 6

2 Answers2

6

By using Java stream, you can use:

String result = words.entrySet().stream()
        .map(entry -> String.format("%s <=> %s", entry.getKey(), entry.getValue()))
        .collect(Collectors.joining(", "));

Or with the simple loop, you can dot it like so:

String comma = "";
for (Map.Entry<String, String> entry : words.entrySet()) {
    System.out.printf("%s%s <=> %s", comma, entry.getKey(), entry.getValue());
    comma = ", ";
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

There are many ways to do this. Here is one way with minimal change to your current code, and minimal performance impact:

boolean first = true;
for (Map.Entry<String, String> entry : words.entrySet()) {
    System.out.printf("%s%s <=> %s", first ? "" : ", ",
                      entry.getKey(), entry.getValue());
    first = false;
}

The trick is to realize that the separator goes between elements of the sequence rather than after them.

(There are some tweaks that would make the above marginally faster, but since it is writing to standard output, it is reasonable to assume that most of the cost of this code will be on the output side.)


@YCF_L's solution is neater if you are familiar with streams, but it has the downside that it will construct a string representing the entire map. If the map is extremely large, that would be undesirable.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216