0

I was wondering if it is possible to do a select * where value is in Java String[] or do I need to build a string of values from the string array first?

I am trying to find the best way of doing this technically without singular selects or building a string of values from the array.

Thanks for your time.

String[] lookupValues = new String[]{"1", "2", "3", "4"};
Select * from database where value in (lookupvalues)
2
  • Can you elaborate on what you're trying to do? Do you want do filter an String[]? Commented Jan 29, 2014 at 20:43
  • How are you sending your query from Java to MySQL? Where's the JDBC? Commented Jan 29, 2014 at 20:46

3 Answers 3

1

try Arrays.toString(lookupvalues) or write a utility function.

    public String toString(String[] values, boolean addQuotes) {

        StringBuilder buff = new StringBuilder();
        for(String value : values) {
            if(addQuotes) {
                buff.append(String.format("\"%s\"", value)).append(",");
            } else {
                buff.append(value).append(",");
            }
        }
        buff.deleteCharAt(buff.length()-1); // delete the last comma
        return buff.toString();
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Are you looking to search for a string in array? If yes, you might want to look at Collections.binarySearch() or Arrays.binarySearch() - but please not that the collections or arrays need to be sorted before doing binary search

Comments

0

I know that this is not a direct answer to your question considering only arrays. I suggest you to use Guava since it offers a implementation of filter on Java Collections. Using proven libraries will give you flexibility if you use different kind of filters.

You can easily convert your array into proper collection

String[] lookupValues = new String[]{"1", "2", "3", "4"};
List<String> list = new ArrayList<String>(Arrays.asList(lookupValues));

And filter it with Guava filters:

Collection<String> filtered = Collections2.filter(list,
    Predicates.containsPattern("3"));
print(filtered);

will find

3

If you want filtered collection as a list, you can use this something like this from Guava:

List<String> filteredList = Lists.newArrayList(Collections2.filter(
    list, Predicates.containsPattern("3")));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.