Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining a List<String> in Java with commas and "and"

Given a list

List<String> l = new ArrayList<String>(); l.add("one"); l.add("two"); l.add("three"); 

I have a method

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;     } 

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 "); 

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"); 
like image 552
slipset Avatar asked Nov 24 '11 09:11

slipset


People also ask

How do you concatenate elements in a list in Java?

extends E> c) method of the class java. util. ArrayList appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. Using this method you can concatenate two lists.

How do I join a list of strings?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


2 Answers

In Java 8 you can use String.join() like following:

Collection<String> elements = ....; String result = String.join(", ", elements); 
like image 59
Ali Dehghani Avatar answered Oct 17 '22 03:10

Ali Dehghani


With Java 8, you can use streams with joiners.

Collection<String> strings; ... String commaDelimited = strings.stream().collect(Collectors.joining(",")); // use strings.parallelStream() instead, if you think //   there are gains to be had by doing fork/join 
like image 21
CppNoob Avatar answered Oct 17 '22 03:10

CppNoob