I have to retrieve values from database and add it into arraylist .Here is my code ..
ArrayList country = new ArrayList();
strQuery = "Select * from country";
rs = conexiondb.Consulta(strQuery);
while (rs.next()) {
String toc = rs.getString("country");
country.add(toc);
}
out.print(country);
System.out.println(country);
out.close();
i have added all the values retrieved from database into country..and here is the values present in the country..
[APAC, North America, South America, Europe]
Now as per my need i have to remove space after each comma values and make it like this..
[APAC,North America,South America,Europe]
Please guys help me to solve this..
Thanks in advance.
What you are seeing is how ArrayList formats it's contents, not the results of your query, try something like...
for (String name : country) {
System.out.println("[" + name + "]");
}
To check. If there are still spaces in the output, then you can use String#trim when you extract the values from the database and before you place them in the List
If you need to format the String, you need to provide you own mechanism, for example...
List<String> values = new ArrayList<>();
values.add("APAC");
values.add("North America");
values.add("South America");
values.add("Europe");
System.out.println(values);
StringBuilder sb = new StringBuilder(128);
for (String value : values) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(value);
}
sb.insert(0, "[");
sb.append("]");
System.out.println(sb);
Which outputs...
[APAC, North America, South America, Europe]
[APAC,North America,South America,Europe]
You are relying on the default formatting provided by ArrayList.toString(). Don't do that. Write your own formatting code.
The spaces aren't coming from the database at all, they are just a function of the way ArrayList.toString() (and in fact all of the JDK Collection classes which inherit from AbstractCollection) pretty prints your list.
You can tell this is the case either by looking at the documentation for this class, or by noting that there is no space before the initial [.
I recommend Guava Joiner for full control over your output.
Joiner.on(',').join(country);
will give the String you want.
ArrayList toString method prints the collection using a space after each comma. If you want to print the list without spaces, then you need to write a new method to do that.
If memory is not the issue. store it in a separate StringBuilder
This should not be a difficult problem. It is just a bit of manupluation.
In case you want comma separated value to have space storing in arraylist will give you that.
If you need the result to start and end with square braces with inside values being comma separated without any space in between the strings.
ArrayList <String> country = new ArrayList<String>();
ArrayList country = new ArrayList();
strQuery = "Select * from country";
rs = conexiondb.Consulta(strQuery);
StringBuilder commaSeparated = new StringBuilder("[");
while (rs.next()) {
String toc = (rs.getString("country")).trim();
commaSeparated.append(toc).append(",");
country.add(toc);
}
commaSeparated.append("]");
out.print(country);
System.out.println(country);
System.out.println(commaSeparated.toString());
out.close();
Related
I have been given an API that saves data in a field in the following order: ["Hello","world","confused"] .
I don't know how to format like this before I pass my data as an input?
The text values are taken from a checkbox.
If I save it in an array I get "[hello,world,confused]" format.
You save the raw values into a single String. YOu have to save it as an array, list or a map. I will not show map usage in this answer. Example:
//Get the Strings
String ex1 = "hello";
String ex2 = "world";
String ex3 = "confused";
//Array
String[] s = new String[3];
s[0] = ex1;
s[1] = ex2;
s[2] = ex3;
//List
List<String> list = new ArrayList<>();
list.add(ex1);
list.add(ex2);
list.add(ex3);
Now, if you send it over the internet and receive the data, send it as raw strings. Then convert it to List for easability. If the amount of Strings vary, this is the easiest way:
StringBuilder sb = new StringBuilder();
sb.append("[\"");
for(int i = 0; i < list.size()/*or .length if it is an array*/; i++){
if(i == list.size() - 1)
sb.append(list.get(i)/*or array[i]*/ + "\"]");
else
sb.append(list.get(i)/*or array[i]*/ + "\",\"");
}
String f = sb.toString();
//Display list: TextView, print to console, whatever you want to do
These are put in a List because it is much easier to loop a list than to manually add every String.
If the amount of Strings are static, you can use String.format:
String f = String.format(Locale.ENGLISH, "[\"%s\",\"%s\",\"%s\"]", ex1, ex2, ex3);
If I somehow misunderstood your question, let me know so I can edit my answer
I have a string where i need to place the values from the list,But when i for loop the list i will get one value at a iteration.
public class Test2 {
public static void main(String[] args) throws ParseException, JSONException {
List<String> value=new ArrayList<String>();
value.add("RAM");
value.add("26");
value.add("INDIA");
for(int i=0;i<value.size();i++){
String template="My name is "+value.get(i) +" age is "+value.get(i)+" country is"+value.get(i);
System.out.println(value.get(i));
}
o/p should be like this: String ="My name is +"+RAM +"age is "+26+"Country is"+INDIA;
}
}
You don't need a for loop, simply access the elements using index of the List as shown below:
System.out.println("My name is "+value.get(0) +
" age is "+value.get(1)+" country is"+value.get(2));
Also, I suggest you use StringBuilder for appending strings which is a best practice, as shown below:
StringBuilder output = new StringBuilder();
output.append("My name is ").append(value.get(0)).append(" age is ").
append(value.get(1)).append(" country is ").append(value.get(2));
System.out.println(output.toString());
What's happening is that in each iteration you're taking the i-th element of the list and you're placing it in all the positions of your String template.
As #javaguy says, there's no need to use a for loop if you only have those three items in your list, and another solution is to use String.format:
String template = "My name is %s age is %s country is %s";
String output = String.format(template, value.get(0), value.get(1), value.get(2));
It's probably a bit slower (interesting discussion here) but performances don't seem to be relevant in your case, so the choiche between the two options would be mostly based on personal taste.
You do not need any loop! Also you do not need any array list I am sorry but I could fully understand what exactly you need but I this code will help you:
List<String> value = new ArrayList<String>();
value.add("RAM");
value.add("26");
value.add("INDIA");
String template = "My name is " + value.get(0) + " age is " + value.get(1) + " country is" + value.get(2);
System.out.println(template);
// o/p should be like this: String ="My name is +"+RAM +"age is
// "+26+"Country is"+INDIA;
I got a problem with this code:
for (String functionChain : stringCollection) {
lblSource.setText(functionChain);
System.out.print(functionChain);
}
I want to set the text to lblSource as a "chain" of all the collected strings.
It does work with the System.out , i mean it does output as I want but it doesnt Set the Text to the Label, it only sets the LAST valor of the array.
Why is this happening? I mean, the system.out is fine and i am taking same variable "functionChain"... However the output is different in the system.out as in the label.
Get the old value first and concatenate.
lblSource.setText(lblSource.getText() + functionChain);
setText() does what it sounds like it does: it sets the text of the label.
Try this instead:
String s = "";
for (String functionChain : stringCollection) {
s += functionChain;
System.out.print(functionChain);
}
lblSource.setText(s);
lblSource.setText(functionChain) will over write the existing value with new value.
To have all the values of string collection , loop through the string collection , append the values and then set the value to lblSource.
eg :
StringBuilder sb = new StringBuilder();
loop through the collection.
sb.append(each value);
sb.append (",") // a separator if required
then
lblSource.setText(sb.toString())
I have a program in which I have to retrieve data from database. I have retrieved it in the form of String. This String Contains Some 100 Values. Now I have to compare these values with the values of the String given by me . If The values matches then it should execute the if condition, otherwise not.
here is my code...
String str = "9035"; Manually Given by me.
AreaCode = rs.getString("AreaCode"); Retrieved from database with 100 records..
I am using if(AreaCode.equals(str)) but it's not working....
The way to debug this is as follows:
String str = "9035";
while (rs.next()) {
String areaCode = rs.getString("AreaCode");
if(str.equals(areaCode)){
System.out.println("!!!!!!It matched: " + str);
break;
} else {
System.out.println("No match with: " + areaCode);
}
}
From you question it looks like you are just comparing the first record, what you need to do is iterate through each result as above and compare. Once you find the record you exit the loop with the break statement.
Of course a better solution is to do a select using a where clause that include the areaCode, if you get a record back then it is in there, if not, the you know it isn't.
Something like
select count(0) as tot from your_table_name where AreaCode = '9035'
and then with the ResultSet of that do
if(rs.getInt("AreaCode") != 0){
//found the/a match
}
If your Areacode contains 100 records, Areacode is some kind of collection, I assume. You cannot compare a collection with string "str"
If Areacode is a collection, then iterate over the collection and then compare it with the 'str'
This might help you get started.
Iterator itr = Areacode.iterator();
while(itr.hasNext()){
if(AreaCode.equals(str)){
//do something
}
}
Instead of iterating - add another 'equal' condition to the query.
It will be for sure easier and more efficient.
So in Java, I know that str.endsWith(suffix) tests if str ends with something. Let's say I have a text with the line "You are old" in it. How would I take the "old" and set it as a variable so I can print it out in the console?
I know I could do:
if(str.endsWith("old")){
String age = "old";
}
But then I'm going to have more options, so then I'd have to do:
if(str.endsWith("option1")){
String age = "option1";
}
if(str.endsWith("option2")){
String age = "option2";
}
...
Is there a more efficient and less verbose way to check the end of strings over writing many, possibly hundreds, of if statements
Format:
setting: option
setting2: option2
setting3: option3 ...
Regardless of what "option" is, I want to set it to a variable.
If you are working with sentences and you want to get the word, do
String word = str.substring(str.lastIndexOf(" "));
You may need a +1 after the lastIndexOf() to leave the space out.
Is that what you are looking for?
Open your file and read the line with the readLine() method. Then to get the last word of the string you can do as it is suggested here
You mean like:
String phrase = "old";
if(str.endsWith(old)){
Is this what you're looking for?
List<String> suffixes = new ArrayList<String>();
suffixes.add("old");
suffixes.add("young");
for(String s: suffixes)
{
if (str.endsWith(s))
{
String age = s;
// .... more of your code here...
}
}
If you're worried about repeating very similar code, the answer is always (99%) to create a function,
So in your case, you could do the following:
public void myNewFunction(String this, String that){
if(this.endsWith(that)){
String this = that;
}
}
...
String str = "age: old";
myNewFunction(str, "old"); //Will change str
myNewFunction(str, "new"); //Will NOT change str
And if that is too much, you can create a class which will do all of this for you. Inside the class, you can keep track of a list of keywords. Then, create a method which will compare a given word with each keyword. That way, you can call the same function on a number of strings, with no additional parameters.
You could use this Java code to solve your problem:
String suffix = "old";
if(str.endsWith(suffix)) {
System.out.println(suffix);
}