今天有人问我,怎么样将List转成sql中使用的in条件,好像用过,但是又记不清了,因此特意记下来
select * from table where colum in(条件)
List<String> ids = Arrays.asList("1", "2","3"); StringBuffer idsStr = new StringBuffer(); for (int i = 0; i < ids.size(); i++) { if (i > 0) { idsStr.append(","); } idsStr.append("'").append(ids.get(i)).append("'"); } System.out.println(idsStr);
输出
'1','2','3'
补充
(1)直接 toString()
List<String> ids = Arrays.asList("1", "2","3"); System.out.println(ids.toString());
输出
[1, 2, 3]
(2)List转String,拼接
List<String> ids = Arrays.asList("1", "2","3"); System.out.println(String.join(",",ids));
输出
1,2,3
(3)String转list,分割
String astr = "a,b,c"; List<String> listString = Arrays.asList(astr.split("','")); System.out.println(listString.toString());