Give comma separated strings as input to sql "IN" clause [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
creating comma seperated string to be given as input to sql “IN” clause
HI,
i have to implement multiple select dropdown,and the selected values shud be formatted to be input to "IN" clause of sql.
Am storing the selected values in a string.But there is no delimiter between values ,so i cannot split the string.Are there any other methods for the string formatting.

Fun solution: Add the values to ArrayList or LinkedList, the call toString(). And replace '['->'(', replace ']'->')'.

If you had a collection of strings and then copied them to 1 string without delimiters you cannot separate them again. Just do not do this. If you still have problems please send more details about your task.

If you know the values of the dropdown and all values are unique and not subsets of each other, then you can use String#contains() or regular expressions to test, which values have been selected.
But it's by far easier to simply add some trivial delimiter (like the common ";") while concatenating the String that holds the selection.
Example for the contains approach
String[] legalValues = {"YES","NO","MAYBE"};
String result = getSelection(); // returns a String like "MAYBEYES"
StringBuilder inClauseBuilder = new StringBuilder();
boolean isFirst = true;
for (String legalValue:legalValues) {
if (!result.contains(legalValue)
continue;
if (isFirst) {
isFirst = false;
} else {
inClauseBuilder.append(",");
}
inClauseBuilder.append("\"").append(legalValue).append("\"");
}
String inClause = inClauseBuilder.toString();
Note - this approach will fail as soon as you have legal values like
String[] legalValues = {"YES","NO","MAYBE-YES", "MAYBE-NO"};
^^^ ^^ ^^^ ^^

Related

(JAVA) If replacing previous if statement

Quick question. I have the following code:
//Cookie
if (mType.getText().toString().toLowerCase().contains("Cookie")) {
mResults.setText(mType.getText().toString().replaceAll("(?i)\\bCookie\\b", "Dough"));
}
//Cola
if (mType.getText().toString().toLowerCase().contains("Cola")) {
mResults.setText(mType.getText().toString().replaceAll("(?i)\\bCola\\b", "Sprite"));
}
I have a script which allows me to replace certain words from user input. When a user inputs the word "Cookie", the script replaces the word with "Dough". If, however, the user types in "Cookie Cola", the script only replaces the word "Cola" with "Sprite" and discards the previous if statement which replaces the word "Cookie".
So, how can I create a script which allows me to replace multiple words from input without discarding previous if statements?
You can just store it into a variable.
like:
String value = (mType.getText().toString().toLowerCase();
if(value.contains("soda")) { value = value.replaceAll("soda","cola"); }
if(...) {...}
But. Technically you are doing more work than necessary. You can chain your replacements.
String value = (mType.getText().toString().toLowerCase();
value = value.replaceAll("soda","cola").replaceAll("...","...")... //Etc.
To answer your question- in both ifs, you're calling replace on mType.getText(). But you aren't changing that value. So you're doing the second replace on the original string. Here's how the code should look like:
String text = mType.getText().toString();
text = text.replaceAll("(?i)\\bCookie\\b", "Dough");
text = text.replaceAll("(?i)\\bCola\\b", "Sprite"));
mResults.setText(text);
Chaining together multiple String.replaceAll() statements can achieve the same result without the need for if statements. For example
String result = mType.getText.toString().toLowerCase();
result = result.replaceAll("cola", "sprite")
.replaceAll("cookie", "dough"); // And so on...
mResults.setText(result);

Conditional statement in java8 forEach loop [duplicate]

This question already has answers here:
Java: convert List<String> to a join()d String
(23 answers)
Closed 6 years ago.
I have string which contain number of department separated by comma.
I have to feed this data to sql 'IN' clause.
I want conditional check for last element, I do not want to append 'comma' after
last element. I don`t know how to use condition inside java 8 forEach loop.
public String getDeptInClauseParameters(String depts){
StringBuilder deptsInParameter= new StringBuilder();
Stream<String> stream= Arrays.stream(depts.split(","));
stream.forEach(dept -> deptsInParameter.append("'").append(dept).append("' , "));
return deptsInParameter.toString();
}
You can use the Collectors.joining(delimiter, prefix, suffix).
delimiter the delimiter to be used between each element
prefix the sequence of characters to be used at the beginning of the joined result
suffix the sequence of characters to be used at the end of the joined result
Example:-
String depts = "Dept1,Dept2";
Stream<String> stream = Arrays.stream(depts.split(","));
System.out.println(stream.collect(Collectors.joining("','", "'", "'")));
This will print 'Dept1','Dept2'as output, hope it helps

How to append semi-colon on to each element in an ArrayList<String> [duplicate]

This question already has answers here:
Optimize this ArrayList join method
(9 answers)
Closed 6 years ago.
I am currently trying to append a semi-colon onto the end of each element in an ArrayList .
The code:
ArrayList<String> emailAddresses = new ArrayList<String>();
public void getEmailAddresses() throws InterruptedException {
driver.findElement(By.className("userlink-0")).click();
String emailAddress = driver.findElement(By.id("email")).getText();
emailAddresses.add(emailAddress);
hs.addAll(emailAddresses);
emailAddresses.clear();
emailAddresses.addAll(hs);
}
Eventually I will be taking this list of email addresses and outputting it to the recipients field for sending an email using Java. Hence why I am trying to append semi-colons to the elements in order to separate the email addresses.
Thanks
Assuming that you use Java 8, you could do that using the Stream API with joining(CharSequence delimiter) as collector allowing to concatenate the input elements, separated by the specified delimiter, in encounter order as next:
String emails = emailAddresses.stream().collect(Collectors.joining(";"));
As a primitive solution you may use:
for (int i = 0; i < emailAddresses.size(); i++) {
emailAddresses.set(i, emailAddresses.get(i).concat(";"));
}
Removing commas with semi-colons doesn't sounds to me a full proof solution that will grantee to not break in future. Since that requires doing syso on list and then use regex to replace commas and brackets. Instead I'll use StringBuilder, iterate over the list and append semi-colons.
StringBuilder str = new StringBuilder();
for(int i=0; i< emailAddresses.size(); i++ )
{
str.append(emailAddresses.get(i));
//to skip last emailAddress
if(i+1 == emailAddresses.size())
continue;
str.append(";");
}
System.out.println(str.toString());
You can add semicolon to each element while adding them to ArrayList. But suppose you want to do some processing later on, so now you have to take care of that extra semicoln you have added.
So a better solution could be, just add all element as they are and just print below line on the recipient filed where you want them:
System.out.println(emailAddresses .toString().replace("[", "").replace("]", "").replace(",", ";"));
If any problem ask in comment section.

Only display part of string after a certain word in Java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I am trying to only display data after a certain static word (in)
Example:
String jobName = job.getDescription();
returns the following:
XYZ/LMNOP in ABCEFG
I only want the data after the "in" in this scenario. However the XYZ/LMNOP is different in almost every case so I cannot simply call out that section of the string.
You can use split() in the String class.
String jobName = job.getDescription();
String[] parts = jobName.split("in"); { "XYZ/LMNOP", "ABCEFG" }
String before = parts[0]; // XYZ/LMNOP
String after = parts[1]; // ABCEFG
Find index of "in" in the string and then use the string from that particular index+3 to last.
int k = p.indexOf("in");
System.out.println(p.substring(k+3));
index+3 because "i", "n" , " " are 3 characters.
First you need to understand your strings possible data values. If it is always <some_text> in <some_text> then there are muliple ways as other users have mentioned.
Here is another way, whih is bit simpler
String[] strArray = job.getDescription().split(" "); //splits array on spaces
System.out.println(strArray[2]);
try using this
String search = " in ";
String d = job.getDescription();
d = d.substring(d.indexOf(search) + search.length(), d.length());
Outputs, given the inputs:
[find something in a string] -> [a string]
[finding something in a string] -> [a string] // note findINg, that does not match
The search key can be changed to simply in if desired, or left as is to match the question posted to avoid an accidental in in a word.
If you so choose, you can also use .toLower() on getDescription() if you want to be case insensitive when matching the word in as well.

String split method is leaving empty tokens at the beginning [duplicate]

This question already has answers here:
Java String.split() sometimes giving blank strings
(3 answers)
Closed 9 years ago.
I have a string
String text="abc19xyz87nag";
I need to get only the numbers out of it, so I applied "\\D+" regex as below,
String text="abc19xyz87nag";
String[] tks=text.split("\\D+");
But I see a empty token in the beginning of the array
How ever I have found out two other solutions anyway as below
Using scanner
Scanner sc = new Scanner(text).useDelimiter("\\D+");
while(sc.hasNext()) {
System.out.println(sc.nextInt());
}
Using Pattern and Matcher
Matcher m = Pattern.compile("\\d+").matcher(text);
while (m.find()) {
System.out.println(m.group());
}
So Why string split is leaving empty token at the beginning?
Do I need to change the regex to avoid it?
Any help is appreciated
It is a design decision to not discard empty strings at the beginning. The rationale is that split() is often used with data like
item1, item2, item3
(here the delimitter is ',') and you want to keep the non-null items at their positions.
Now, suppose you parse lines with 3 items like above, where the first and the last are optional. If split would discard both leading and trailing empty strings, and you get 2 elements back, you couldn't decide whther the input was:
, item2, item3
or
item1, item2
By only discarding empty strings at the end, you know that every non-empty string is at its correct position.
Your Regex should be like
[^\d]
Hope it helps
String s = "smt-ing we want to split");
StringTokenizer st = new StringTokenizer();
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
You can do some validation to remove that empty String.
String text="abc19xyz87nag";
String[] tks=text.split("\\D+");
List<String> numList=new ArrayList<>();
for(String i:tks){
if(!"".equals(i)){
numList.add(i);
}
}

Categories

Resources