如何打印没有尾随逗号的地图?
我找不到我的问题的答案,所以我希望你能帮助我。
有没有办法在没有逗号的情况下打印它?
for (Map.Entry<String, String> entry : words.entrySet()) {
System.out.printf("%s <=> %s, ", entry.getKey(), entry.getValue());
}
回答
通过使用 Java 流,您可以使用:
String result = words.entrySet().stream()
.map(entry -> String.format("%s <=> %s", entry.getKey(), entry.getValue()))
.collect(Collectors.joining(", "));
或者使用简单的循环,你可以这样点:
String comma = "";
for (Map.Entry<String, String> entry : words.entrySet()) {
System.out.printf("%s%s <=> %s", comma, entry.getKey(), entry.getValue());
comma = ", ";
}