How to add or insert ' (single quotes) for every string in a list in which strings are separated by commas using Java

前端 未结 10 1229
夕颜
夕颜 2021-02-05 06:12

I have a list as below

[url1,url2,url3,url4] 

This list will be based on multiple selection from drop down list of HTML. So list size i.e., lis

相关标签:
10条回答
  • 2021-02-05 07:08

    You can use Java 8 utility class java.util.StringJoiner.

    This class specifically introduced to format list of string values.

    For example:

    StringJoiner joiner = new StringJoiner("','", "'", "'");
            joiner.add("url1");
            joiner.add("url2");
            joiner.add("url3");
            joiner.add("url4");
            System.out.println(joiner);
    

    Output

    'url1','url2','url3','url4'
    

    Note that, in constructor of StringJoiner,

    StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
    

    we are passing single quote as prefix and suffix to satisfy your specific requirement.

    0 讨论(0)
  • 2021-02-05 07:11

    Most fast and efficient way to do this

    Ex.

    ArrayList<String> a=[url1,url2,url3,url4];
    
    String s  ="'"+a.toString().replace("[","").replace("]", "").replace(" ","").replace(",","','")+"'";
    
    0 讨论(0)
  • 2021-02-05 07:12

    Have one Util.java file or if you already have all common util stuff then just add these static methods

    for single quote

    public static String singleQuote(String str) {
            return (str != null ? "'" + str + "'" : null);
    }
    

    for double quotes

    public static String doubleQuotes(String str) {
            return (str != null ? "\"" + str + "\"" : null);
    }
    
    0 讨论(0)
  • 2021-02-05 07:13

    Using Java 8 Streams:

    String[] array = {"url1", "url2", "url3", "url4"}
    
    Stream.of(array).collect(Collectors.joining("','", "'", "'"));
    
    0 讨论(0)
提交回复
热议问题