Avoid prefix suffix for blank string in Collectors.joining [duplicate] - java

This question already has answers here:
Add prefix and suffix to Collectors.joining() only if there are multiple items present
(3 answers)
Custom Collector to join stream on delimiter, suffix and prefix only if stream is not empty suffix
(1 answer)
How to generalize utility function using method references/java 8
(2 answers)
Closed 3 years ago.
I have a requirement to read the string from a list and join them with ','. Also need to add comma in prefix and suffix of the total output string.
Example : If list contans["a","b","c"] then output would be ",a,b,c,".
Now thats perfectly working with Collectors.joining but if the list does not contains any value then also in output strting I am getting ",," as output because prefix and suffix is added.
Now what I want is to avoid the prefix and suffix in case if blank String. So, any suggestion?
List<String> list = new ArrayList<>();
String result = list.stream().collect(Collectors.joining(",", ",", ","));
System.out.println(result);
Thanks in Advance.

Just check if the list has elements:
List<String> list = new ArrayList<>();
String result = "";
if (!list.isEmpty())
{
result = list.stream().collect(Collectors.joining(",",",",","));
}
System.out.println(result);

Related

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.

Converting a JavaScript Array that's been JSON.stringify to a Java Array [duplicate]

This question already has answers here:
How to parse a JSON and turn its values into an Array?
(3 answers)
Closed 7 years ago.
Hello I'm trying to convert an Array which has been sent from my JavaScript after going through the JSON.stringify method. I'm currently experimenting/looking at a regex solution for it but anything that returns a normal JAVA Array<Integer> with the values between the "" works.
JAVA Code:
private ArrayList<Integer> convertJSONArrayStringtoArray(String jsonArrayString){
Matcher m = Pattern.compile(".*\\\"(.*)\\\".*").matcher(jsonArrayString);
while(m.find()) {
System.out.println("convertJSONtoArray: " + m.group(1));
}
return null;
}
String Composition (Note that the string is not a JSON object that holds a array, just a simple array):
["12441","3324","11584","3337","25739","25810"]
With using Gson, you can do:
List<String> result = new Gson().fromJson( jsonArrayString, List.class );
It it is a one-shot and you feel using a whole library is overkill :
String input = "[\"12441\",\"3324\",\"11584\",\"3337\",\"25739\",\"25810\"]";
String[] tokens = input.substring(1, input.length()-2).split(",");
List<Integer> ints = Arrays.asList(tokens).stream().map(s -> Integer.parseInt(s.substring(1, s.length()-1))).collect(Collectors.toList());

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

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

Categories

Resources