Is there a way to join strings, each with a specific surrounding string?

后端 未结 3 803
孤街浪徒
孤街浪徒 2021-01-13 13:35

I\'m looking to use guava\'s Joiner to join List into one string, but with surrounding strings around each one in the list. So I want

相关标签:
3条回答
  • 2021-01-13 14:17

    The way to do this is with a transform, first:

     Joiner.on(", ").join(Iterables.transform(names, new Function<String, String>() {
       public String apply(String str) { return "your guest " + str + " is here"; }
     }));
    
    0 讨论(0)
  • 2021-01-13 14:20

    How about

        String str = "your guest " + Joiner.on(" is here, your guest ").join(names) + " is here";
    
    0 讨论(0)
  • 2021-01-13 14:20

    if Joiner is not a must you can use String.format()

    public static void main(String[] args) {
            List<String> names = Arrays.asList("John", "Mary", "Henry");
            StringBuilder builder = new StringBuilder();
    
            for(int i=0; i<names.size();i++){
                builder.append(String.format("your guest %s is here, ", names.get(i)));
            }
            System.out.println(builder.substring(0,builder.length()-2).toString());
        }
    
    0 讨论(0)
提交回复
热议问题