给出如下列表:
列表与LT;字符串> names = Lists.newArrayList(“乔治”,“约翰”,“保罗”,“林戈”)
我想将它转换为这样的字符串:
乔治,约翰,保罗和林戈
我可以用相当笨拙的StringBuilder这样做:
String nameList = names.stream().collect(joining(",")); if (nameList.contains(",")) { StringBuilder builder = new StringBuilder(nameList); builder.replace(nameList.lastIndexOf(','),nameList.lastIndexOf(',') + 1," and"); return builder.toString(); }
是否有更优雅的方法?如果需要,我不介意使用库.
笔记:
解决方法
正如您已经完成的大部分内容,我将介绍第二种方法“replaceLast”,它目前为止不在JDK for java.lang.String中:
import java.util.List; import java.util.stream.Collectors; public final class StringUtils { private static final String AND = " and "; private static final String COMMA = ","; // your initial call wrapped with a replaceLast call public static String asLiteralNumeration(List<String> strings) { return replaceLast(strings.stream().collect(Collectors.joining(COMMA)),COMMA,AND); } public static String replaceLast(String text,String regex,String replacement) { return text.replaceFirst("(?s)" + regex + "(?!.*?" + regex + ")",replacement); } }
您也可以更改分隔符和参数.到目前为止测试您的要求:
@org.junit.Test public void test() { List<String> names = Arrays.asList("George","John","Paul","Ringo"); assertEquals("George,John,Paul and Ringo",StringUtils.asLiteralNumeration(names)); List<String> oneItemList = Arrays.asList("Paul"); assertEquals("Paul",StringUtils.asLiteralNumeration(oneItemList)); List<String> emptyList = Arrays.asList(""); assertEquals("",StringUtils.asLiteralNumeration(emptyList)); }