java 如何从JAVA中的字符串数组列表中的单引号中创建逗号分隔的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27941956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:40:19  来源:igfitidea点击:

how to create comma separated string in single quotes from arraylist of string in JAVA

javaarraysarraylist

提问by LoneWolf

I have requirement in Java to fire a query on MS SQL like

我需要在 Java 中触发对 MS SQL 的查询,例如

select * from customer 
where customer.name in ('abc', 'xyz', ...,'pqr');

But I have this IN clause values in the form of ArrayList of String. For ex: the list look like {"abc","xyz",...,"pqr"}

但是我有这个 IN 子句值的形式为 ArrayList of String。例如:列表看起来像 {"abc","xyz",...,"pqr"}

I created a Prepared Statement :

我创建了一个准备好的声明:

 PreparedStatement pStmt = conn.prepareStatement(select * from customer 
    where customer.name in (?));
String list= StringUtils.join(namesList, ",");
pStmt.setString(1,list);
rs = pStmt.executeQuery();

But the listis like "abc,xyz,..,pqr", but I want it as "'abc','xyz',..,'pqr'"so that I can pass it to Prepares Statement.

但是列表就像"abc,xyz,..,pqr",但我希望它是"'abc','xyz',..,'pqr'"以便我可以将它传递给 Prepares Statement。

How to do it in JAva with out GUAVA helper libraries.

如何在没有 GUAVA 帮助程序库的情况下在 JAva 中做到这一点。

Thanks in Advance!!

提前致谢!!

回答by Jonck van der Kogel

I know this is a really old post but just in case someone is looking for how you could do this in a Java 8 way:

我知道这是一篇很老的帖子,但以防万一有人正在寻找如何以 Java 8 方式执行此操作:

private String join(List<String> namesList) {
    return String.join(",", namesList
            .stream()
            .map(name -> ("'" + name + "'"))
            .collect(Collectors.toList()));
}

回答by Szarpul

For converting the string you can try this:

要转换字符串,您可以尝试以下操作:

String list= StringUtils.join(namesList, "','");
list = "'" + list + "'";

But i dont thing it's a good idea to pass one string for multiple params.

但我不认为为多个参数传递一个字符串是个好主意。

回答by Eran

Even if you formatted the String as you wish, it won't work. You can't replace one placeholder in the PreparedStatementwith multiple values.

即使您按照自己的意愿格式化了字符串,它也不会起作用。您不能PreparedStatement用多个值替换 中的一个占位符。

You should build the PreparedStatementdynamically to have as many placeholders as there are elements in your input list.

您应该PreparedStatement动态构建以拥有与输入列表中的元素一样多的占位符。

I'd do something like this :

我会做这样的事情:

StringBuilder scmd = new StringBuilder ();
scmd.append ("select * from customer where customer.name in ( ");
for (int i = 0; i < namesList.size(); i++) {
  if (i > 0)
    scmd.append (',');
  scmd.append ('?');
}
scmd.append (")");
PreparedStatement stmt = connection.prepareStatement(scmd.toString());

if (namesList.size() > 0) {
    for (int i = 0; i < namesList.size(); i++) {
        stmt.setString (i + 1, namesList.get(i));
    }
}
rs = stmt.executeQuery();

回答by Igorock

List<String> nameList = ...    
String result = nameList.stream().collect(Collectors.joining("','", "'", "'"));

回答by OldCurmudgeon

You can use a simple separator for this type of activity. Essentially you want an object that evaluates to "" the first time around but changes after the first request to return a defined string.

您可以为此类活动使用简单的分隔符。本质上,您需要一个对象,该对象第一次评估为“”,但在第一次请求返回定义的字符串后发生变化。

public class SimpleSeparator<T> {
  private final String sepString;
  boolean first = true;

  public SimpleSeparator(final String sep) {
    this.sepString = sep;
  }

  public String sep() {
    // Return empty string first and then the separator on every subsequent invocation.
    if (first) {
      first = false;
      return "";
    }
    return sepString;
  }

  public static void main(String[] args) {
    SimpleSeparator sep = new SimpleSeparator("','");
    System.out.print("[");
    for ( int i = 0; i < 10; i++ ) {
      System.out.print(sep.sep()+i);
    }
    System.out.print("]");
  }

}

回答by Leandro Orílio

I guess the simplest way to do it is using expression language like that:

我想最简单的方法是使用这样的表达式语言:

 String[] strings = {"a", "b", "c"};
 String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "\'").replace(", ", "\',\'" );