加入List< String>在Java中用逗号和"and"表示 [英] 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,它产生"1、2和3". 我的问题是,是否有一个标准的方法(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);
这篇关于加入List< String>在Java中用逗号和"and"表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!