Joining a List in Java with commas and “and”

后端 未结 8 2018
梦谈多话
梦谈多话 2020-12-01 11:48

Given a list

List l = new ArrayList();
l.add(\"one\");
l.add(\"two\");
l.add(\"three\");

I have a method

<
相关标签:
8条回答
  • 2020-12-01 12:29

    What about join from: org.apache.commons.lang.StringUtils

    Example:

    StringUtils.join(new String[] { "one", "two", "three" }, ", "); // one, two, three
    

    To have "and" or ", and" you can simple replace the last comma.

    0 讨论(0)
  • 2020-12-01 12:30

    Other answers talk about "replacing the last comma", which isn't safe in case the last term itself contains a comma.

    Rather than use a library, you can just use one (albeit long) line of JDK code:

    public static String join(List<String> msgs) {
        return msgs == null || msgs.size() == 0 ? "" : msgs.size() == 1 ? msgs.get(0) : msgs.subList(0, msgs.size() - 1).toString().replaceAll("^.|.$", "") + " and " + msgs.get(msgs.size() - 1);
    }
    

    See a live demo of this code handling all edge cases.


    FYI, here's a more readable two-liner:

    public static String join(List<String> msgs) {
        int size = msgs == null ? 0 : msgs.size();
        return size == 0 ? "" : size == 1 ? msgs.get(0) : msgs.subList(0, --size).toString().replaceAll("^.|.$", "") + " and " + msgs.get(size);
    }
    
    0 讨论(0)
提交回复
热议问题