Java - Append quotes to strings in an array and join strings in an array

前端 未结 7 731
后悔当初
后悔当初 2020-12-13 00:04

I would like to append double quotes to strings in an array and then later join them as a single string (retaining the quotes). Is there any String library which does this?

7条回答
  •  一整个雨季
    2020-12-13 00:43

    A more generic way would be sth. like:

    private static class QuoteFunction {
        char quote;
    
        public QuoteFunction(char quote) {
            super();
            this.quote = quote;
        }
    
        Function func = new Function() {
            @Override
            public String apply(F s) {
                return new StringBuilder(s.toString().length()+2).append(quote).append(s).append(quote).toString();
            }
        };
    
        public Function getFunction() {
            return func;
        }
    }
    

    ... call it via the following function

    public static  String asString(Iterable lst, String delimiter, Character quote) {
        QuoteFunction quoteFunc = new QuoteFunction(quote);
        Joiner joiner = Joiner.on(delimiter).skipNulls();
        return joiner.join(Iterables.transform(lst, quoteFunc.getFunction()));
    }
    

提交回复
热议问题