加入列表<String>在 Java 中使用逗号和“和" [英] Joining a List<String> in Java with commas and "and"
问题描述
给定一个列表
List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");
我有办法
String join(List<String> messages) {
if (messages.isEmpty()) return "";
if (messages.size() == 1) return messages.get(0);
String message = "";
message = StringUtils.join(messages.subList(0, messages.size() -2), ", ");
message = message + (messages.size() > 2 ? ", " : "") + StringUtils.join(messages.subList(messages.size() -2, messages.size()), ", and ");
return message;
}
对于 l,它产生一、二和三".我的问题是,是否有相同的标准(apache-commons)方法?,例如
which, for l, produces "one, two, and three". My question is, is there a standard (apache-commons) method that does the same?, eg
WhatEverUtils.join(l, ", ", ", and ");
澄清一下.我的问题不是让这种方法起作用.它按我的意愿工作,经过测试,一切正常.我的问题是我找不到一些实现此类功能的类似 apache-commons 的模块.这让我感到惊讶,因为我不可能是第一个需要它的人.
To clarify. My problem is not getting this method to work. It works just as I want it to, it's tested and all is well. My problem is that I could not find some apache-commons-like module which implements such functionality. Which surprises me, since I cannot be the first one to need this.
但也许其他人都刚刚做过
But then maybe everyone else has just done
StringUtils.join(l, ", ").replaceAll(lastCommaRegex, ", and");
推荐答案
在 Java 8 中你可以使用 String.join()
如下:
In Java 8 you can use String.join()
like following:
Collection<String> elements = ....;
String result = String.join(", ", elements);
这篇关于加入列表<String>在 Java 中使用逗号和“和"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!