Joining a List in Java with commas and “and”

后端 未结 8 2022
梦谈多话
梦谈多话 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 12:20

    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
    

提交回复
热议问题