Join in Java

Source: Internet
Author: User

Function: Join () function: combines an array into a string using the selected separator. This is the method provided in JavaScript. net contains a similar string. the join method can concatenate the specified separator string between each element of the specified string array to generate a single concatenation string, because most of the problems encountered are for the string array, so it is barely enough. But there is no such method in Java. Here we provide a solution.

 

Public static string join (Collection S, string delimiter ){
Stringbuffer buffer = new stringbuffer ();
Iterator iter = S. iterator ();
While (ITER. hasnext ()){
Buffer. append (ITER. Next ());
If (ITER. hasnext ()){
Buffer. append (delimiter );
}
}
Return buffer. tostring ();
}

If we remove the if statement from the loop, the efficiency will be improved.

 

Public static string join (abstractcollection S, string delimiter ){
Stringbuffer buffer = new stringbuffer ();
Iterator iter = S. iterator ();
If (ITER. hasnext ()){
Buffer. append (ITER. Next ());
While (ITER. hasnext ()){
Buffer. append (delimiter );
Buffer. append (ITER. Next ());
}
}
Return buffer. tostring ();
}

This looks more comprehensive.

 

Public static string join (abstractcollection <string> S, string delimiter ){
If (S. isempty () Return "";
Iterator <string> iter = S. iterator ();
Stringbuffer buffer = new stringbuffer (ITER. Next ());
While (ITER. hasnext () buffer. append (delimiter). append (ITER. Next ());
Return buffer. tostring ();
}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.