Joining string array together, from certain argument, into a string? [duplicate] - java

This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 6 years ago.
Here is my String array containing the following:
"message" "player" "how" "are" "you"
I am wanting to join the "how" "are" "you" part of the String[] and I am currently doing the following:
String msg = "";
for (int i = 2; i < args.length; i++)
{
msg = msg + args[i] + " ";
}
Util.messagePlayer(player, msg);
So my question is, is there a better/more efficient way of doing this?

Yes, there is a better way, everytime you are iterating that array, new String objects are getting created(because Strings are immutable), however this one is a short String, so the efficiency loss is not that considerable,still try to use StringBuilder instead
StringBuilder msg = new StringBuilder();
for (int i = 2; i < args.length; i++)
{
msg.append(args[i] + " ");
}
Util.messagePlayer(player, msg.toString);
For complete details, StringBuilder vs String concatenation in toString() in Java

String objects are immutable ones in Java, hence every time you concatenate two strings, you are creating a new Object this is costly.
Instead, you can use a StringBuilder.
More about how to use it is well described here:
Correct way to use StringBuilder

Related

Java - StringBuilder vs Concatenation of strings [duplicate]

This question already has answers here:
StringBuilder vs String concatenation in toString() in Java
(20 answers)
Closed 4 years ago.
The question is simple, what is better for avoiding of non-appropriated memory using? For example, let's say that we've a String s = "Test" and we'd like to add 1 to it so it becomes Test1. We all know that s gets a memory location and if we use StringBuilder, Test1 will get a new memory address or it'll remain at s's place, and what if we use concat?
One line concatenations are optimized and converted to StringBuilder under the hood. Memory wise is the same thing, but the manual concatenation is more concise.
// the two declarations are basically the same
// JVM will optimize this to StringBuilder
String test = "test";
test += "test";
StringBuilder test = new StringBuilder();
test.append("test");
On the other hand, if you don't do trivial concatenations, you will be better off with StringBuilder.
// this is worse, JVM won't be able to optimize
String test = "";
for(int i = 0; i < 100; i ++) {
test += "test";
}
// this is better
StringBuilder builder = new StringBuilder();
for(int i = 0; i < 100; i ++) {
builder.append("test");
}

Why string concatenation takes so long time? [duplicate]

This question already has answers here:
StringBuilder vs String concatenation in toString() in Java
(20 answers)
Closed 7 years ago.
I am concatenating a String in a loop but it takes ages, why is that?
for (String object : jsonData) {
counter++;
finalJsonDataStr += object;
}
Variable object is a piece of JSON, up to 70 chars and the loop goes approx 50k times.
I understand some people advice StringBuffer or StringBuilder but this link says, it has no performance improvements: StringBuilder vs String concatenation in toString() in Java
Use a String Builder to append to strings.
When you concatenate, Java is actually creating a new String with the results of the concatenation.
Do it multiple times and you are creating gazillion of strings for nothing.
Try:
StringBuilder sb = new StringBuilder();
for (String object : jsonData) {
counter++;
sb.append(object.toString()); //this does the concatenation internally
//but is very efficient
}
finalJsonDataStr = sb.toString(); //this gives you back the whole string
Remark:
When you do stuff like
myString = "hello " + someStringVariable + " World!" + " My name is " + name;
The compiler is smart enough to replace all that with a single StringBuilder, like:
myString = new StringBuilder("hello ")
.append(someStringVariable)
.append(" World!")
.append(" My name is ")
.append(name).toString();
But for some reason I don't know, it doesn't do it when the concatenation happens inside a loop.
You should use a StringBuffer or a StringBuilder.
When you add Strings with plus, a StringBuilder is created, strings are concatenated and a new String is return with toString() method of the StringBuilder. So image this object creation and string manipulation 50k times. It's much better if you instantiate only one StringBuilder yourself and just append strings...
This answer could be of use to you: concatenation operator (+) vs concat()
Before going to the actual problem, see how internal concatenation works.
String testString ="str"+"ingcon"+"catenation";
If we print the above declared String to console and see, the result is stringconcatenation.Which is correct and the + works fine. Here is out actual question, how does that + symbol did the magic ? ? Is it not a normal mathematical addition of Strings. The below code snippet shows how that code with + actually converts.
StringBuilder compilerGeneratedBuilder = new StringBuilder();
compilerGeneratedBuilder.append("str");
compilerGeneratedBuilder.append("ingcon");
compilerGeneratedBuilder.append("catenation");
String finalString = compilerGeneratedBuilder.toString();
More .....
50K times loop is a descent performance blocker to consider.
In such cases use StringBuilder with append method. Cause concat (+) create a new object every time a new String Builder object. That leads to 50k objects creations.
With single StringBuilder and append method, you can save the time of Objection creation as well as the memory too.

How to delete only commas that appear because of Arrays.toString() [duplicate]

This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 8 years ago.
Replacing square brackets is not a problem, but the problem is with replacing commas,
replace(",", "") , because it does it with all commas in my table and i need to delete only those which appears because of Arrays.toString()
System.out.println( Arrays.toString( product ).replace("[", "").replace("]", "").replace(",", ""));
If there is no way of do that, maybe there are other ways to print my array, like string builder...etc? but i am not sure how to use it
Rather than using Arrays.toString, since you don't want the output it creates, use your own loop:
StringBuilder sb = new StringBuilder(400);
for (int i = 0; i < product.length; ++i) {
sb.append(product[i].toString());
}
String result = sb.toString();
Note I'm using toString on your product entries; there may be a more appropriate choice depending on what those are.
If you want a delimiter (other than ,, obviously), just append it to the StringBuilder as you go:
StringBuilder sb = new StringBuilder(400);
for (int i = 0; i < product.length; ++i) {
if (i > 0) {
sb.append(yourDelimiter);
}
sb.append(product[i].toString());
}
String result = sb.toString();
We dont know what your objects look like in your array, but you shouldnt use Arrays.toString if you dont like the output since its only a helper method to save you some time. Just iterate over your objects with a loop and print them.
There's a great library of apache where you can achieve your goal in one line of code:
org.apache.commons.lang.StringUtils
String delimiter = " ";
StringUtils.join(array, delimiter);

String builder vs string concatenation [duplicate]

This question already has answers here:
StringBuilder vs String concatenation in toString() in Java
(20 answers)
Closed 6 years ago.
What is the benefit and trade-off of using a string builder over pure string concatenation?
new StringBuilder(32).append(str1)
.append(" test: ")
.append(val)
.append(" is changed")
.toString();
vs say
str1 + " test: " + val + " is changed".
str1 is a random 10 character string.
str2 is a random 8 character string.
In your particular example, none because the compiler internally uses StringBuilders to do String concatenation. If the concatenation occurred in a loop, however, the compiler could create several StringBuilder and String objects. For example:
String s= "" ;
for(int i= 0 ; i < 10 ; i++ )
s+= "a" ;
Each time line 3 above is executed, a new StringBuilder object is created, the contents of s appended, "a" appended, and then the StringBuilder is converted into a String to be assigned back to s. A total of 10 StringBuilders and 10 Strings.
Conversely, in
StringBuilder sb= new StringBuilder() ;
for(int i= 0 ; i < 10 ; i++ )
sb.append( "a" );
String s= sb.toString() ;
Only 1 StringBuilder and 1 String are created.
The main reason for this is that the compiler could not be smart enough to understand that the first loop is equivalent to the second and generate more efficient (byte) code. In more complex cases, it's impossible even for the smartest compiler to know. If you absolutely need this optimization, you have to introduce it manually by using StringBuilders explicitly.
The quick answer is the performance:
when you are using native String classes it operates immutable strings, which means when you are writing
String line = "java";
String sufix = " is awesome";
line = line + sufix;
it will create two strings "java" and " is awesome", than create a new third string "java is awesome" from previous two ("java" and "is awesome") which later are likely to be deleted by a garbage collector (because they are no more used in app). That is a slow solution.
More faster solution is an appliance of StringBuffer class which through the smart algorightms that provide a buffer (that is obvious from its name) for merging strings and as a result would not remove the initial string during the concatenation process.
In case you are writing single thread-application (no concurrancy issues during which multiple threads access same object) it is better to apply StringBuilder which has even faster performance than the initial StringBuffer class.

Convert ArrayList <Characters> into a String [duplicate]

This question already has answers here:
Converting ArrayList of Characters to a String?
(12 answers)
Closed 1 year ago.
Is there a simple way of converting an ArrayList that contains only characters into a string? So say we have
ArrayList<Character> arrayListChar = new ArrayList<Character>();
arrayListChar.add(a);
arrayListChar.add(b);
arrayListChar.add(c);
So the array list contains a, b, and c. Ideally what I'd want to do is turn that into a String "abc".
Iterator<Character> it = arrayListChar.iterator();
StringBuilder sb = new StringBuilder();
while(it.hasNext()) {
sb.append(it.next());
}
System.out.println(sb.toString());
You could use Apache Common Lang's StringUtils class. It has a join() function like you find in PHP.
Then the code:
StringUtils.join(arrayListChar, "")
would generate:
abc
int size = list.size();
char[] chars = new char[size];
for (int i = 0; i < size; i++) {
if (list.size() != size) {
throw new ConcurrentModificationException();
}
chars[i] = list.get(i);
}
String s = new String(chars);
Using regex magic:
String result = list.toString().replaceAll(", |\\[|\\]", "");
Get the String representation of the list, which is
[a, b, c]
and then remove the strings "[", "]", and ", ".
You can override it's toString method and implement the String formatting therein.
Override toString method of ArrayList or the better to extend the ArrayList class so that you may use old ArrayList toString() somewhere else in the code
String s = "";
for(Character i : arrayListChar)
s += i;
EDIT - as pointed out already, you should only use code like this if the number of strings to concatenate is small.

Categories