Given a list
List l = new ArrayList();
l.add(\"one\");
l.add(\"two\");
l.add(\"three\");
I have a method
<
Improved version from Bohemian♦'s answer. You can choose to remove the nulled items check on personal preferences.
/** Auto Concat Wrapper
* Wraps a list of string with comma and concat the last element with "and" string.
* E.g: List["A", "B", "C", "D"] -> Output: "A, B, C and D"
* @param elements
*/
public static String join(List elements){
if(elements==null){return "";}
List tmp = new ArrayList<>(elements);
tmp.removeAll(Collections.singleton(null)); //Remove all nulled items
int size = tmp.size();
return size == 0 ? "" : size == 1 ? tmp.get(0) : String.join(", ", tmp.subList(0, --size)).concat(" and ").concat(tmp.get(size));
}
Test results:
List w = Arrays.asList("A");
List x = Arrays.asList("A", "B");
List y = Arrays.asList("A", "B", null, "C");
List z = Arrays.asList("A", "B", "C", "D");
System.out.println(join(w));//A
System.out.println(join(x));//A and B
System.out.println(join(y));//A, B and C
System.out.println(join(z));//A, B, C and D