During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:
在使用数据库的过程中,我注意到我编写了查询字符串,在这个字符串中,我必须在list/array/collection的where子句中设置几个限制。应该是这样的:
select * from customer
where customer.id in (34, 26, ..., 2);
You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.
您可以将其简化为您有字符串集合的问题,并希望在一个字符串中创建一个逗号分隔的字符串列表。
My approach I have used so far is something like that:
我目前使用的方法是这样的:
String result = "";
boolean first = true;
for(String string : collectionOfStrings) {
if(first) {
result+=string;
first=false;
} else {
result+=","+string;
}
}
But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.
但是你可以看到这很丑陋。您无法在第一眼看到发生了什么,特别是当构造的字符串(就像每个SQL查询一样)变得复杂时。
What is your (more) elegant way?
你(更)优雅的方式是什么?
31 个解决方案
#1
82
Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.
由于字符串是不可变的,所以如果要修改代码中的字符串,您可能需要使用StringBuilder类。
The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.
可以将StringBuilder类视为一个可变字符串对象,当其内容被更改时,该对象将分配更多内存。
The original suggestion in the question can be written even more clearly and efficiently, by taking care of the redundant trailing comma:
通过处理冗余的尾逗号,可以更清楚、更有效地写出问题中的原始建议:
StringBuilder result = new StringBuilder();
for(String string : collectionOfStrings) {
result.append(string);
result.append(",");
}
return result.length() > 0 ? result.substring(0, result.length() - 1): "";
#2
84
Use the Google Guava API's join
method:
使用谷歌番石榴API的连接方法:
Joiner.on(",").join(collectionOfStrings);
#3
71
I just looked at code that did this today. This is a variation on AviewAnew's answer.
我只是看了今天的代码。这是AviewAnew回答的一个变体。
collectionOfStrings = /* source string collection */;
String csList = StringUtils.join(collectionOfStrings.toArray(), ",");
The StringUtils ( <-- commons.lang 2.x, or commons.lang 3.x link) we used is from Apache Commons.
StringUtils(<——commons)朗2。x,或者共享。郎朗3。我们使用的是Apache Commons。
#4
42
The way I write that loop is:
我写这个循环的方法是:
StringBuilder buff = new StringBuilder();
String sep = "";
for (String str : strs) {
buff.append(sep);
buff.append(str);
sep = ",";
}
return buff.toString();
Don't worry about the performance of sep. An assignment is very fast. Hotspot tends to peel off the first iteration of a loop anyway (as it often has to deal with oddities such as null and mono/bimorphic inlining checks).
不要担心sep的性能,作业非常快。Hotspot总是倾向于剥离循环的第一次迭代(因为它经常要处理一些奇怪的事情,比如null和mono/ bimorphy内联检查)。
If you use it lots (more than once), put it in a shared method.
如果您大量使用它(不止一次),请将它放在共享方法中。
There is another question on * dealing with how to insert a list of ids into an SQL statement.
关于如何将id列表插入到SQL语句中,*还有一个问题。
#5
34
Since Java 8, you can use:
由于Java 8,您可以使用:
String String.join(CharSequence delimiter, CharSequence... elements)
- 字符串的字符串。加入(CharSequence进行分隔符,CharSequence进行…元素)
String String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
- 字符串的字符串。加入(CharSequence进行分隔符,Iterable < ?扩展CharSequence进行>元素)
-
If you want to take non-
String
s and join them to aString
, you can useCollectors.joining(CharSequence delimiter)
, e.g.:如果您想获取非字符串并将它们连接到字符串,您可以使用收集器。加入(CharSequence进行分隔符),例如:
String joined = anyCollection.stream().map(Object::toString).collect(Collectors.joining(","));
字符串加入= anyCollection.stream(). map(对象::toString).collect(Collectors.joining(","));
#6
10
I found the iterator idiom elegant, because it has a test for more elements (ommited null/empty test for brevity):
我发现迭代器习惯用法很优雅,因为它有更多元素的测试(为了简洁起见,省略了空/空测试):
public static String convert(List<String> list) {
String res = "";
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
res += iterator.next() + (iterator.hasNext() ? "," : "");
}
return res;
}
#7
7
There's a lot of manual solutions to this, but I wanted to reiterate and update Julie's answer above. Use google collections Joiner class.
有很多手动解决方案,但是我想重申一下,并更新上面朱莉的回答。使用谷歌集合连接器类。
Joiner.on(", ").join(34, 26, ..., 2)
It handles var args, iterables and arrays and properly handles separators of more than one char (unlike gimmel's answer). It will also handle null values in your list if you need it to.
它处理var args、iterables和数组,并正确处理多个char的分隔符(不像gimmel的答案)。如果需要,它还将处理列表中的空值。
#8
7
Here's an incredibly generic version that I've built from a combination of the previous suggestions:
这是我根据之前的建议构建的一个非常通用的版本:
public static <T> String buildCommaSeparatedString(Collection<T> values) {
if (values==null || values.isEmpty()) return "";
StringBuilder result = new StringBuilder();
for (T val : values) {
result.append(val);
result.append(",");
}
return result.substring(0, result.length() - 1);
}
#9
7
String.join(", ", collectionOfStrings)
available in the Java8 api.
在Java8 api中可用。
alternative to (without the need to add a google guava dependency):
替代方案(不需要添加谷歌番石榴依赖项):
Joiner.on(",").join(collectionOfStrings);
#10
5
You could try
你可以试试
List collections = Arrays.asList(34, 26, "...", 2);
String asString = collection.toString();
// justValues = "34, 26, ..., 2"
String justValues = asString.substring(1, asString.length()-1);
#11
4
I think it's not a good idea contruct the sql concatenating the where clause values like you are doing :
我认为这不是一个好主意,把sql连接到where子句值,就像你正在做的:
SELECT.... FROM.... WHERE ID IN( value1, value2,....valueN)
选择....从....在ID(value1,value2,....家)
Where valueX comes from a list of Strings.
valueX来自字符串列表。
First, if you are comparing Strings they must be quoted, an this it isn't trivial if the Strings could have a quote inside.
首先,如果你在比较字符串它们必须被引用,如果字符串里面可以有引用的话,这个是很重要的。
Second, if the values comes from the user,or other system, then a SQL injection atack is posible.
其次,如果值来自用户或其他系统,那么可以使用SQL注入atack。
It's a lot more verbose but what you should do is create a String like this:
它要复杂得多,但是你要做的是创建一个这样的字符串:
SELECT.... FROM.... WHERE ID IN( ?, ?,....?)
选择....从....在ID(?,?,.... ?)
and then bind the variables with Statement.setString (nParameter,parameterValue)
然后用语句绑定变量。setString(nParameter parameterValue)
#12
4
This will be the shortest solution so far, except of using Guava or Apache Commons
这将是迄今为止最短的解决方案,除了使用番石榴或Apache Commons
String res = "";
for (String i : values) {
res += res.isEmpty() ? i : ","+i;
}
Good with 0,1 and n element list. But you'll need to check for null list. I use this in GWT, so I'm good without StringBuilder there. And for short lists with just couple of elements its ok too elsewhere ;)
良好的0 1和n元素列表。但是您需要检查空列表。我在GWT中使用这个,所以没有StringBuilder就很好。对于只有几个元素的简短列表,在其他地方也是可以的;
#13
4
In case someone stumbled over this in more recent times, I have added a simple variation using Java 8 reduce()
. It also includes some of the already mentioned solutions by others:
如果最近有人遇到这种情况,我使用Java 8 reduce()添加了一个简单的变体。它还包括其他国家已经提到的一些解决办法:
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Joiner;
public class Dummy {
public static void main(String[] args) {
List<String> strings = Arrays.asList("abc", "de", "fg");
String commaSeparated = strings
.stream()
.reduce((s1, s2) -> {return s1 + "," + s2; })
.get();
System.out.println(commaSeparated);
System.out.println(Joiner.on(',').join(strings));
System.out.println(StringUtils.join(strings, ","));
}
}
#14
3
Just another method to deal with this problem. Not the most short, but it is efficient and gets the job done.
这是处理这个问题的另一种方法。不是最短的,但它是有效的,并且完成了工作。
/**
* Creates a comma-separated list of values from given collection.
*
* @param <T> Value type.
* @param values Value collection.
* @return Comma-separated String of values.
*/
public <T> String toParameterList(Collection<T> values) {
if (values == null || values.isEmpty()) {
return ""; // Depending on how you want to deal with this case...
}
StringBuilder result = new StringBuilder();
Iterator<T> i = values.iterator();
result.append(i.next().toString());
while (i.hasNext()) {
result.append(",").append(i.next().toString());
}
return result.toString();
}
#15
3
In Android you should use this:
在安卓系统中,你应该这样使用:
TextUtils.join(",",collectionOfStrings.toArray());
#16
2
There are some third-party Java libraries that provide string join method, but you probably don't want to start using a library just for something simple like that. I would just create a helper method like this, which I think is a bit better than your version, It uses StringBuffer, which will be more efficient if you need to join many strings, and it works on a collection of any type.
有一些第三方Java库提供了字符串连接方法,但是您可能不希望仅仅为了这样简单的事情而开始使用库。我只需要创建一个像这样的帮助器方法,我认为它比您的版本好一点,它使用StringBuffer,如果您需要连接多个字符串,它将更高效,并且它可以处理任何类型的集合。
public static <T> String join(Collection<T> values)
{
StringBuffer ret = new StringBuffer();
for (T value : values)
{
if (ret.length() > 0) ret.append(",");
ret.append(value);
}
return ret.toString();
}
Another suggestion with using Collection.toString() is shorter, but that relies on Collection.toString() returning a string in a very specific format, which I would personally not want to rely on.
使用Collection.toString()的另一个建议更短,但这依赖于Collection.toString()以一种非常特定的格式返回一个字符串,我个人不希望依赖这种格式。
#17
2
If you use Spring, you can do:
如果你使用春天,你可以做:
StringUtils.arrayToCommaDelimitedString(
collectionOfStrings.toArray()
)
(package org.springframework.util)
(包org.springframework.util)
#18
1
I'm not sure how "sophisticated" this is, but it's certainly a bit shorter. It will work with various different types of collection e.g. Set<Integer>, List<String>, etc.
我不确定这有多“复杂”,但它确实有点短。它可以处理各种不同类型的集合,例如设置
public static final String toSqlList(Collection<?> values) {
String collectionString = values.toString();
// Convert the square brackets produced by Collection.toString() to round brackets used by SQL
return "(" + collectionString.substring(1, collectionString.length() - 1) + ")";
}
Exercise for reader: modify this method so that it correctly handles a null/empty collection :)
读者练习:修改此方法,使其正确地处理空/空集合:)
#19
1
What makes the code ugly is the special-handling for the first case. Most of the lines in this small snippet are devoted, not to doing the code's routine job, but to handling that special case. And that's what alternatives like gimel's solve, by moving the special handling outside the loop. There is one special case (well, you could see both start and end as special cases - but only one of them needs to be treated specially), so handling it inside the loop is unnecessarily complicated.
使代码难看的是第一种情况的特殊处理。这个小代码段中的大部分代码行都用于处理特殊情况,而不是执行代码的常规工作。这就是类似gimel的解决方案,通过将特殊处理移出循环。有一个特殊的情况(嗯,您可以将开始和结束都视为特殊情况——但只有一个需要特别处理),因此在循环中处理它是不必要的复杂。
#20
1
Join 'methods' are available in Arrays and the classes that extend AbstractCollections but doesn't override toString() method (like virtually all collections in java.util)
连接“方法”在数组和扩展AbstractCollections但不覆盖toString()方法的类中是可用的(类似于java.util中的几乎所有集合)
for instance: String s= java.util.Arrays.toString(collectionOfStrings.toArray());
例如:Strings = java.util.Arrays.toString(collection of String . toarray ());
s = s.substing(1, s.length()-1);// [] are guaranteed to be there
s =。substing(1, .length()-1);//[]保证在那里。
that's quite weird way since it works only for numbers alike data sql wise.
这是一种非常奇怪的方式,因为它只适用于类似的数据sql。
#21
1
I've just checked-in a test for my library dollar:
我刚刚签了一个关于我图书馆的钱的测试:
@Test
public void join() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
String string = $(list).join(",");
}
it create a fluent wrapper around lists/arrays/strings/etc using only one static import: $
.
它只使用一个静态导入:$,就可以创建一个流畅的列表/数组/字符串/等等包装器。
NB:
注:
using ranges the previous list can be re-writed as $(1, 5).join(",")
使用范围可以将前面的列表重写为$(1,5).join(",")
#22
1
The nice thing about the IN expression is that if you have repeated values, it does not change the result. So, just duplicate the first item and process the entire list. This assumes that there is at least one item in the list. If there are no items, I'd suggest checking for that first and then not executing the SQL at all.
IN表达式的好处是如果你有重复的值,它不会改变结果。所以,复制第一项并处理整个列表。这假定列表中至少有一个条目。如果没有项,我建议先检查一下,然后再不执行SQL。
This will do the trick, is obvious in what it is doing and does not rely on any external libraries:
这将起到关键作用,这一点在它正在做的事情中是显而易见的,它不依赖任何外部库:
StringBuffer inString = new StringBuffer(listOfIDs.get(0).toString());
for (Long currentID : listOfIDs) {
inString.append(",").append(currentID);
}
#23
1
While I think your best bet is to use Joiner from Guava, if I were to code it by hand I find this approach more elegant that the 'first' flag or chopping the last comma off.
虽然我认为最好的方法是使用来自番石榴的Joiner,但如果我手工编写它,我发现这种方法比“第一个”标记或将最后一个逗号去掉更优雅。
private String commas(Iterable<String> strings) {
StringBuilder buffer = new StringBuilder();
Iterator<String> it = strings.iterator();
if (it.hasNext()) {
buffer.append(it.next());
while (it.hasNext()) {
buffer.append(',');
buffer.append(it.next());
}
}
return buffer.toString();
}
#24
1
if you have an array you can do:
如果你有一个数组,你可以做:
Arrays.asList(parameters).toString()
#25
0
You may be able to use LINQ (to SQL), and you may be able to make use of the Dynamic Query LINQ sample from MS. http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
您可以使用LINQ(到SQL),也可以使用来自http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamiclinq -part- use -the LINQ Dynamic - querylibrary.aspx女士的动态查询LINQ示例
#26
0
java.util.List<String> lista = new java.util.ArrayList<String>();
lista.add("Hola");
lista.add("Julio");
System.out.println(lista.toString().replace('[','(').replace(']',')'));
$~(Hola, Julio)
#27
0
String commaSeparatedNames = namesList.toString().replaceAll( "[\\[|\\]| ]", "" ); // replace [ or ] or blank
The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space).
字符串表示由集合元素的列表组成,其迭代器按其返回的顺序返回这些元素,并以方括号括起来(“[]”)。相邻的元素由字符“,”(逗号和空格)分隔。
AbstractCollection javadoc
AbstractCollection javadoc
#28
0
List token=new ArrayList(result); final StringBuilder builder = new StringBuilder();
令牌列表= new ArrayList(结果);最终的StringBuilder =新的StringBuilder();
for (int i =0; i < tokens.size(); i++){
builder.append(tokens.get(i));
if(i != tokens.size()-1){
builder.append(TOKEN_DELIMITER);
}
}
builder.toString();
builder.toString();
#29
0
Another option, based on what I see here (with slight modifications).
另一个选项,基于我在这里看到的(稍微修改)。
public static String toString(int[] numbers) {
StringBuilder res = new StringBuilder();
for (int number : numbers) {
if (res.length() != 0) {
res.append(',');
}
res.append(number);
}
return res.toString();
}
#30
0
There is an easy way. You can get your result in a single line.
有一个简单的方法。您可以在一行中得到您的结果。
String memberIdsModifiedForQuery = memberIds.toString().replace("[", "(").replace("]", ")");
To get complete idea check the code below
要获得完整的想法,请查看下面的代码
public static void main(String[] args) {
List<Integer>memberIds=new ArrayList<Integer>(); //This contain member ids we want to process
//adding some sample values for example
memberIds.add(3);
memberIds.add(4);
memberIds.add(2);
String memberIdsModifiedForQuery = memberIds.toString().replace("[", "(").replace("]", ")"); //here you will get (3,4,5) That you can directly use in query
System.out.println(memberIdsModifiedForQuery);
String exampleQuery="select * from customer where customer.id in "+memberIdsModifiedForQuery+" ";
}
#1
82
Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.
由于字符串是不可变的,所以如果要修改代码中的字符串,您可能需要使用StringBuilder类。
The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.
可以将StringBuilder类视为一个可变字符串对象,当其内容被更改时,该对象将分配更多内存。
The original suggestion in the question can be written even more clearly and efficiently, by taking care of the redundant trailing comma:
通过处理冗余的尾逗号,可以更清楚、更有效地写出问题中的原始建议:
StringBuilder result = new StringBuilder();
for(String string : collectionOfStrings) {
result.append(string);
result.append(",");
}
return result.length() > 0 ? result.substring(0, result.length() - 1): "";
#2
84
Use the Google Guava API's join
method:
使用谷歌番石榴API的连接方法:
Joiner.on(",").join(collectionOfStrings);
#3
71
I just looked at code that did this today. This is a variation on AviewAnew's answer.
我只是看了今天的代码。这是AviewAnew回答的一个变体。
collectionOfStrings = /* source string collection */;
String csList = StringUtils.join(collectionOfStrings.toArray(), ",");
The StringUtils ( <-- commons.lang 2.x, or commons.lang 3.x link) we used is from Apache Commons.
StringUtils(<——commons)朗2。x,或者共享。郎朗3。我们使用的是Apache Commons。
#4
42
The way I write that loop is:
我写这个循环的方法是:
StringBuilder buff = new StringBuilder();
String sep = "";
for (String str : strs) {
buff.append(sep);
buff.append(str);
sep = ",";
}
return buff.toString();
Don't worry about the performance of sep. An assignment is very fast. Hotspot tends to peel off the first iteration of a loop anyway (as it often has to deal with oddities such as null and mono/bimorphic inlining checks).
不要担心sep的性能,作业非常快。Hotspot总是倾向于剥离循环的第一次迭代(因为它经常要处理一些奇怪的事情,比如null和mono/ bimorphy内联检查)。
If you use it lots (more than once), put it in a shared method.
如果您大量使用它(不止一次),请将它放在共享方法中。
There is another question on * dealing with how to insert a list of ids into an SQL statement.
关于如何将id列表插入到SQL语句中,*还有一个问题。
#5
34
Since Java 8, you can use:
由于Java 8,您可以使用:
String String.join(CharSequence delimiter, CharSequence... elements)
- 字符串的字符串。加入(CharSequence进行分隔符,CharSequence进行…元素)
String String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
- 字符串的字符串。加入(CharSequence进行分隔符,Iterable < ?扩展CharSequence进行>元素)
-
If you want to take non-
String
s and join them to aString
, you can useCollectors.joining(CharSequence delimiter)
, e.g.:如果您想获取非字符串并将它们连接到字符串,您可以使用收集器。加入(CharSequence进行分隔符),例如:
String joined = anyCollection.stream().map(Object::toString).collect(Collectors.joining(","));
字符串加入= anyCollection.stream(). map(对象::toString).collect(Collectors.joining(","));
#6
10
I found the iterator idiom elegant, because it has a test for more elements (ommited null/empty test for brevity):
我发现迭代器习惯用法很优雅,因为它有更多元素的测试(为了简洁起见,省略了空/空测试):
public static String convert(List<String> list) {
String res = "";
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
res += iterator.next() + (iterator.hasNext() ? "," : "");
}
return res;
}
#7
7
There's a lot of manual solutions to this, but I wanted to reiterate and update Julie's answer above. Use google collections Joiner class.
有很多手动解决方案,但是我想重申一下,并更新上面朱莉的回答。使用谷歌集合连接器类。
Joiner.on(", ").join(34, 26, ..., 2)
It handles var args, iterables and arrays and properly handles separators of more than one char (unlike gimmel's answer). It will also handle null values in your list if you need it to.
它处理var args、iterables和数组,并正确处理多个char的分隔符(不像gimmel的答案)。如果需要,它还将处理列表中的空值。
#8
7
Here's an incredibly generic version that I've built from a combination of the previous suggestions:
这是我根据之前的建议构建的一个非常通用的版本:
public static <T> String buildCommaSeparatedString(Collection<T> values) {
if (values==null || values.isEmpty()) return "";
StringBuilder result = new StringBuilder();
for (T val : values) {
result.append(val);
result.append(",");
}
return result.substring(0, result.length() - 1);
}
#9
7
String.join(", ", collectionOfStrings)
available in the Java8 api.
在Java8 api中可用。
alternative to (without the need to add a google guava dependency):
替代方案(不需要添加谷歌番石榴依赖项):
Joiner.on(",").join(collectionOfStrings);
#10
5
You could try
你可以试试
List collections = Arrays.asList(34, 26, "...", 2);
String asString = collection.toString();
// justValues = "34, 26, ..., 2"
String justValues = asString.substring(1, asString.length()-1);
#11
4
I think it's not a good idea contruct the sql concatenating the where clause values like you are doing :
我认为这不是一个好主意,把sql连接到where子句值,就像你正在做的:
SELECT.... FROM.... WHERE ID IN( value1, value2,....valueN)
选择....从....在ID(value1,value2,....家)
Where valueX comes from a list of Strings.
valueX来自字符串列表。
First, if you are comparing Strings they must be quoted, an this it isn't trivial if the Strings could have a quote inside.
首先,如果你在比较字符串它们必须被引用,如果字符串里面可以有引用的话,这个是很重要的。
Second, if the values comes from the user,or other system, then a SQL injection atack is posible.
其次,如果值来自用户或其他系统,那么可以使用SQL注入atack。
It's a lot more verbose but what you should do is create a String like this:
它要复杂得多,但是你要做的是创建一个这样的字符串:
SELECT.... FROM.... WHERE ID IN( ?, ?,....?)
选择....从....在ID(?,?,.... ?)
and then bind the variables with Statement.setString (nParameter,parameterValue)
然后用语句绑定变量。setString(nParameter parameterValue)
#12
4
This will be the shortest solution so far, except of using Guava or Apache Commons
这将是迄今为止最短的解决方案,除了使用番石榴或Apache Commons
String res = "";
for (String i : values) {
res += res.isEmpty() ? i : ","+i;
}
Good with 0,1 and n element list. But you'll need to check for null list. I use this in GWT, so I'm good without StringBuilder there. And for short lists with just couple of elements its ok too elsewhere ;)
良好的0 1和n元素列表。但是您需要检查空列表。我在GWT中使用这个,所以没有StringBuilder就很好。对于只有几个元素的简短列表,在其他地方也是可以的;
#13
4
In case someone stumbled over this in more recent times, I have added a simple variation using Java 8 reduce()
. It also includes some of the already mentioned solutions by others:
如果最近有人遇到这种情况,我使用Java 8 reduce()添加了一个简单的变体。它还包括其他国家已经提到的一些解决办法:
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Joiner;
public class Dummy {
public static void main(String[] args) {
List<String> strings = Arrays.asList("abc", "de", "fg");
String commaSeparated = strings
.stream()
.reduce((s1, s2) -> {return s1 + "," + s2; })
.get();
System.out.println(commaSeparated);
System.out.println(Joiner.on(',').join(strings));
System.out.println(StringUtils.join(strings, ","));
}
}
#14
3
Just another method to deal with this problem. Not the most short, but it is efficient and gets the job done.
这是处理这个问题的另一种方法。不是最短的,但它是有效的,并且完成了工作。
/**
* Creates a comma-separated list of values from given collection.
*
* @param <T> Value type.
* @param values Value collection.
* @return Comma-separated String of values.
*/
public <T> String toParameterList(Collection<T> values) {
if (values == null || values.isEmpty()) {
return ""; // Depending on how you want to deal with this case...
}
StringBuilder result = new StringBuilder();
Iterator<T> i = values.iterator();
result.append(i.next().toString());
while (i.hasNext()) {
result.append(",").append(i.next().toString());
}
return result.toString();
}
#15
3
In Android you should use this:
在安卓系统中,你应该这样使用:
TextUtils.join(",",collectionOfStrings.toArray());
#16
2
There are some third-party Java libraries that provide string join method, but you probably don't want to start using a library just for something simple like that. I would just create a helper method like this, which I think is a bit better than your version, It uses StringBuffer, which will be more efficient if you need to join many strings, and it works on a collection of any type.
有一些第三方Java库提供了字符串连接方法,但是您可能不希望仅仅为了这样简单的事情而开始使用库。我只需要创建一个像这样的帮助器方法,我认为它比您的版本好一点,它使用StringBuffer,如果您需要连接多个字符串,它将更高效,并且它可以处理任何类型的集合。
public static <T> String join(Collection<T> values)
{
StringBuffer ret = new StringBuffer();
for (T value : values)
{
if (ret.length() > 0) ret.append(",");
ret.append(value);
}
return ret.toString();
}
Another suggestion with using Collection.toString() is shorter, but that relies on Collection.toString() returning a string in a very specific format, which I would personally not want to rely on.
使用Collection.toString()的另一个建议更短,但这依赖于Collection.toString()以一种非常特定的格式返回一个字符串,我个人不希望依赖这种格式。
#17
2
If you use Spring, you can do:
如果你使用春天,你可以做:
StringUtils.arrayToCommaDelimitedString(
collectionOfStrings.toArray()
)
(package org.springframework.util)
(包org.springframework.util)
#18
1
I'm not sure how "sophisticated" this is, but it's certainly a bit shorter. It will work with various different types of collection e.g. Set<Integer>, List<String>, etc.
我不确定这有多“复杂”,但它确实有点短。它可以处理各种不同类型的集合,例如设置
public static final String toSqlList(Collection<?> values) {
String collectionString = values.toString();
// Convert the square brackets produced by Collection.toString() to round brackets used by SQL
return "(" + collectionString.substring(1, collectionString.length() - 1) + ")";
}
Exercise for reader: modify this method so that it correctly handles a null/empty collection :)
读者练习:修改此方法,使其正确地处理空/空集合:)
#19
1
What makes the code ugly is the special-handling for the first case. Most of the lines in this small snippet are devoted, not to doing the code's routine job, but to handling that special case. And that's what alternatives like gimel's solve, by moving the special handling outside the loop. There is one special case (well, you could see both start and end as special cases - but only one of them needs to be treated specially), so handling it inside the loop is unnecessarily complicated.
使代码难看的是第一种情况的特殊处理。这个小代码段中的大部分代码行都用于处理特殊情况,而不是执行代码的常规工作。这就是类似gimel的解决方案,通过将特殊处理移出循环。有一个特殊的情况(嗯,您可以将开始和结束都视为特殊情况——但只有一个需要特别处理),因此在循环中处理它是不必要的复杂。
#20
1
Join 'methods' are available in Arrays and the classes that extend AbstractCollections but doesn't override toString() method (like virtually all collections in java.util)
连接“方法”在数组和扩展AbstractCollections但不覆盖toString()方法的类中是可用的(类似于java.util中的几乎所有集合)
for instance: String s= java.util.Arrays.toString(collectionOfStrings.toArray());
例如:Strings = java.util.Arrays.toString(collection of String . toarray ());
s = s.substing(1, s.length()-1);// [] are guaranteed to be there
s =。substing(1, .length()-1);//[]保证在那里。
that's quite weird way since it works only for numbers alike data sql wise.
这是一种非常奇怪的方式,因为它只适用于类似的数据sql。
#21
1
I've just checked-in a test for my library dollar:
我刚刚签了一个关于我图书馆的钱的测试:
@Test
public void join() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
String string = $(list).join(",");
}
it create a fluent wrapper around lists/arrays/strings/etc using only one static import: $
.
它只使用一个静态导入:$,就可以创建一个流畅的列表/数组/字符串/等等包装器。
NB:
注:
using ranges the previous list can be re-writed as $(1, 5).join(",")
使用范围可以将前面的列表重写为$(1,5).join(",")
#22
1
The nice thing about the IN expression is that if you have repeated values, it does not change the result. So, just duplicate the first item and process the entire list. This assumes that there is at least one item in the list. If there are no items, I'd suggest checking for that first and then not executing the SQL at all.
IN表达式的好处是如果你有重复的值,它不会改变结果。所以,复制第一项并处理整个列表。这假定列表中至少有一个条目。如果没有项,我建议先检查一下,然后再不执行SQL。
This will do the trick, is obvious in what it is doing and does not rely on any external libraries:
这将起到关键作用,这一点在它正在做的事情中是显而易见的,它不依赖任何外部库:
StringBuffer inString = new StringBuffer(listOfIDs.get(0).toString());
for (Long currentID : listOfIDs) {
inString.append(",").append(currentID);
}
#23
1
While I think your best bet is to use Joiner from Guava, if I were to code it by hand I find this approach more elegant that the 'first' flag or chopping the last comma off.
虽然我认为最好的方法是使用来自番石榴的Joiner,但如果我手工编写它,我发现这种方法比“第一个”标记或将最后一个逗号去掉更优雅。
private String commas(Iterable<String> strings) {
StringBuilder buffer = new StringBuilder();
Iterator<String> it = strings.iterator();
if (it.hasNext()) {
buffer.append(it.next());
while (it.hasNext()) {
buffer.append(',');
buffer.append(it.next());
}
}
return buffer.toString();
}
#24
1
if you have an array you can do:
如果你有一个数组,你可以做:
Arrays.asList(parameters).toString()
#25
0
You may be able to use LINQ (to SQL), and you may be able to make use of the Dynamic Query LINQ sample from MS. http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
您可以使用LINQ(到SQL),也可以使用来自http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamiclinq -part- use -the LINQ Dynamic - querylibrary.aspx女士的动态查询LINQ示例
#26
0
java.util.List<String> lista = new java.util.ArrayList<String>();
lista.add("Hola");
lista.add("Julio");
System.out.println(lista.toString().replace('[','(').replace(']',')'));
$~(Hola, Julio)
#27
0
String commaSeparatedNames = namesList.toString().replaceAll( "[\\[|\\]| ]", "" ); // replace [ or ] or blank
The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space).
字符串表示由集合元素的列表组成,其迭代器按其返回的顺序返回这些元素,并以方括号括起来(“[]”)。相邻的元素由字符“,”(逗号和空格)分隔。
AbstractCollection javadoc
AbstractCollection javadoc
#28
0
List token=new ArrayList(result); final StringBuilder builder = new StringBuilder();
令牌列表= new ArrayList(结果);最终的StringBuilder =新的StringBuilder();
for (int i =0; i < tokens.size(); i++){
builder.append(tokens.get(i));
if(i != tokens.size()-1){
builder.append(TOKEN_DELIMITER);
}
}
builder.toString();
builder.toString();
#29
0
Another option, based on what I see here (with slight modifications).
另一个选项,基于我在这里看到的(稍微修改)。
public static String toString(int[] numbers) {
StringBuilder res = new StringBuilder();
for (int number : numbers) {
if (res.length() != 0) {
res.append(',');
}
res.append(number);
}
return res.toString();
}
#30
0
There is an easy way. You can get your result in a single line.
有一个简单的方法。您可以在一行中得到您的结果。
String memberIdsModifiedForQuery = memberIds.toString().replace("[", "(").replace("]", ")");
To get complete idea check the code below
要获得完整的想法,请查看下面的代码
public static void main(String[] args) {
List<Integer>memberIds=new ArrayList<Integer>(); //This contain member ids we want to process
//adding some sample values for example
memberIds.add(3);
memberIds.add(4);
memberIds.add(2);
String memberIdsModifiedForQuery = memberIds.toString().replace("[", "(").replace("]", ")"); //here you will get (3,4,5) That you can directly use in query
System.out.println(memberIdsModifiedForQuery);
String exampleQuery="select * from customer where customer.id in "+memberIdsModifiedForQuery+" ";
}