从Collection / Array / List创建以逗号分隔的字符串的最复杂方法? [英] The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

查看:180
本文介绍了从Collection / Array / List创建以逗号分隔的字符串的最复杂方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用数据库的过程中,我注意到我编写了查询字符串,在这个字符串中,我必须在list / array / collection的where子句中加入几个限制。应该是这样的:

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:

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;
    }
}

但是你可以看到非常丑陋。您无法看到第一眼看到的情况,特别是当构造的字符串(如每个SQL查询)变得复杂时。

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.

您的(更多)优雅方式是什么?

What is your (more) elegant way?

推荐答案

由于字符串是不可变的,如果要在代码中更改String,可能需要使用StringBuilder类。

Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.

StringBuilder类可以看作是一个可变的String对象,当它的内容被改变时会分配更多的内存。

The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.

通过处理冗余尾随逗号,可以更清楚有效地写出问题中的原始建议:

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): "";

这篇关于从Collection / Array / List创建以逗号分隔的字符串的最复杂方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆