Reputation: 5398
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)
Upvotes: 0
Views: 3634
Reputation: 10707
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 Collection
s. 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")));
Upvotes: 0
Reputation: 6154
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();
}
Upvotes: 1
Reputation: 803
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
Upvotes: 0