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
Related
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);
This question already has answers here:
Split string with dot as delimiter
(13 answers)
Closed 5 years ago.
I'm trying to fill an array of 2 elements with a element from another array, split by "." but it doesn't fill (for instance, the input is "83.105" and i need the first element to be "83" and the second "105"). When i try to get the 0 element from numberParts array it shows out of bounds exception. I'm really confused since this method is working on C# but not Java.
String[] inputNumbers = console.nextLine().split(" ");
String[] numberParts = inputNumbers[0].split(".");
System.out.println(numberParts[0]);
Dot (.) is a char that must be escaped in the split method.
why? because is a reserved character in regex
if not, splitting will return an empty array
String myString = "83.105";
String[] x = myString.split("\\.");
System.out.println(x[0]);
System.out.println(x[1]);
This question already has answers here:
Split string with dot as delimiter
(13 answers)
Closed 7 years ago.
I need to be able to split a single word string like "x.y" into an array of size 2 where the "." occurs, so the array would look like ["x", "y"]. What I've tried is:
String word = "hello.world";
String[] split = word.split(".")
return split.length == 2;
but this seems to just return an empty array (false). How would I go about doing this? Thanks.
Repalce this
String[] split = word.split(".")
with
String[] split = word.split("\\.")
. (dot) has a special meaning in regex so you need to escape it if you want to use it as a literal to split.
This question already has an answer here:
Split string on spaces in Java, except if between quotes (i.e. treat \"hello world\" as one token) [duplicate]
(1 answer)
Closed 8 years ago.
I have a String(freeText) "Manas \"Jaikant IBM\"". I want to split into two strings:
String normalMatch="Manas";
String exactMatch="Jaikant IBM";
It means that String normalMatch contains Manas and String exactMatch contains Jaikant IBM.
i am using the split() method of String class in Java
String[] splittedText= freeText.split("\\s");
I am getting 3 string elements but i need 2 string elements only.
Use substring instead of split:
int index = freeText.indexOf(" ");
String normalMatch = freeText.substring(0,index);
String exactMatch = freeText.substring(index); // endIndex == freeText.length())
Split on quotes(") then, you will get Manas and Jaikant IBM and can ignore the 3rd value.
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"};
^^^ ^^ ^^^ ^^