Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

During my work with databases, I noticed that I write query strings and in these 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 a collection of strings and want to create a comma-separated list of these strings in just one string.

The 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.

What is your (more) elegant way?

1 Answer

0 votes
by (40.7k points)

As strings are immutable, you can use the StringBuilder class if you want to alter the String in the code. The StringBuilder class can be considered as a mutable String object which is used to allocate more memory when its content is altered. The question should be written even more clearly and efficiently, by taking care of the redundant trailing comma like this:

    StringBuilder result = new StringBuilder();

    for(String string : collectionOfStrings) {

        result.append(string);

        result.append(",");

    }

    return result.length() > 0 ? result.substring(0, result.length() - 1): "";

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 23, 2019 in SQL by Tech4ever (20.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...