Question
Is there a standard method in Apache Commons that joins a List<String> with commas and 'and', similar to my custom implementation?
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;
}
Answer
In Java, joining elements of a List<String> with specific delimiters like commas and 'and' is a common requirement in text processing. While Apache Commons Lang offers powerful string manipulation utilities, it lacks a built-in method for this specific format. However, custom solutions can achieve the desired output effectively.
import org.apache.commons.lang3.StringUtils;
public static String joinListWithAnd(List<String> list) {
if (list.isEmpty()) return "";
if (list.size() == 1) return list.get(0);
String result = StringUtils.join(list.subList(0, list.size() - 1), ", ");
result += " and " + list.get(list.size() - 1);
return result;
}
Causes
- Lack of a built-in Apache Commons method for joining lists with custom delimiters.
- Misunderstanding of existing utilities and their capabilities.
Solutions
- Consider writing a utility method like the one you provided.
- Use existing libraries with custom modifications, like StringUtils, to achieve similar results.
Common Mistakes
Mistake: Using incorrect delimiters and not accounting for the last 'and' properly.
Solution: Ensure the last item is prefixed with 'and' and the rest are joined with commas.
Mistake: Assuming Apache Commons has a direct method for this functionality.
Solution: Implement a custom joining method as shown in the code snippet.
Helpers
- Java List join
- Apache Commons join example
- join two lists with commas and and
- Java string manipulation
- StringUtils join Java