What's the best way to build a string of delimited items in Java?

前端 未结 30 2203
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i

30条回答
  •  感情败类
    2020-11-22 06:18

    The Google's Guava library has com.google.common.base.Joiner class which helps to solve such tasks.

    Samples:

    "My pets are: " + Joiner.on(", ").join(Arrays.asList("rabbit", "parrot", "dog")); 
    // returns "My pets are: rabbit, parrot, dog"
    
    Joiner.on(" AND ").join(Arrays.asList("field1=1" , "field2=2", "field3=3"));
    // returns "field1=1 AND field2=2 AND field3=3"
    
    Joiner.on(",").skipNulls().join(Arrays.asList("London", "Moscow", null, "New York", null, "Paris"));
    // returns "London,Moscow,New York,Paris"
    
    Joiner.on(", ").useForNull("Team held a draw").join(Arrays.asList("FC Barcelona", "FC Bayern", null, null, "Chelsea FC", "AC Milan"));
    // returns "FC Barcelona, FC Bayern, Team held a draw, Team held a draw, Chelsea FC, AC Milan"
    

    Here is an article about Guava's string utilities.

提交回复
热议问题