Joining a List in Java with commas and “and”

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

    I like using Guava for this purpose. Neat and very useful:

    Joiner.on(",").join(myList)
    

    This kind of code has been written time and time again and you should rather be freed implementing your specific implementation logic.

    If you use maven, herewith the dependency:

    
        com.google.guava
        guava
        28.1-jre
    
    

    It has a bunch of other wonderful cool features too!

    This will produce the string "one, two, and three".

    List originalList = Arrays.asList("one", "two", "three");
    Joiner.on(", ")
        .join(originalList.subList(0, originalList.size() - 1))
        .concat(", and ")
        .concat(originalList.get(originalList.size() - 1));
    

提交回复
热议问题