Java – how do I concatenate list items but use different delimiters for the last item?
•
Java
The following list is given:
List and lt; String > Names = lists Newarraylist ("George", "John", "Paul", "Ringo")
I want to convert it to such a string:
George, John, Paul and Ringo
I can do this with a rather clumsy 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(); }
Is there a more elegant way? I don't mind using the library if necessary
Notes:
>I can use the old for loop with index, but I'm not looking for such a solution > there is no comma in the value (name)
Solution
As you have completed most of the content, I will introduce the second method "replacelast", which is not in JDK for Java so far In 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); } }
You can also change the separator and parameters Test your requirements so far:
@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)); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码