Joining a List in Java with commas and “and”

后端 未结 8 2020
梦谈多话
梦谈多话 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:22

    I don't know any Apache String joiner that can support adding and in the joined String.

    Here's an untested code that will do what you asked:

    public static String join(String separator, List mList, boolean includeAndInText) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
    
        for (String m: mList) {
            if (includeAndInText && (count + 1 != mList.size())) {
                sb.append (" and ");
            }
    
            sb.append(m);
            count++;
            if (count < mList.size()) {
                sp.append(separator);
            }       
        }
    
        return sb.toString();
    }
    

提交回复
热议问题