วิธีที่ 1: ใช้ StringBuffer (Classic)
public class ArrayToString {
public static void main(String[] args) {
String[] stringArray = {"Hello ", "how", "are", "you", "welcome", "to", "Tutorialspoint"};
StringBuffer sb = new StringBuffer();
for (int i = 0; i < stringArray.length; i++) {
sb.append(stringArray[i]);
}
String result = sb.toString();
System.out.println(result);
}
}
ผลลัพธ์
Hello how are you welcome to Tutorialspoint
วิธีที่ 2: ใช้ Arrays.toString() (ไม่แนะนำสำหรับ join)
Arrays.toString() คืนค่ารูปแบบ [elem1, elem2, elem3] มี bracket และ comma - ไม่ใช่ join แบบตรงไปตรงมา
String str = Arrays.toString(stringArray);
// ผลลัพธ์: [Hello , how, are, you, welcome, to, Tutorialspoint]
วิธีที่ 3: ใช้ StringJoiner (Java 8+) - แนะนำ
StringJoiner สร้าง sequence ของ characters คั่นด้วย delimiter ที่กำหนด
import java.util.StringJoiner;
public class ArrayToStringJoiner {
public static void main(String[] args) {
String[] stringArray = {"Hello", "how", "are", "you", "welcome", "to", "Tutorialspoint"};
StringJoiner joiner = new StringJoiner(" "); // delimiter = space
for (String s : stringArray) {
joiner.add(s);
}
String result = joiner.toString();
System.out.println(result);
}
}
ผลลัพธ์
Hello how are you welcome to Tutorialspoint
วิธีที่ 4: ใช้ String.join() (Java 8+) - สั้นที่สุด
String[] stringArray = {"Hello", "how", "are", "you", "welcome", "to", "Tutorialspoint"};
String result = String.join(" ", stringArray);
System.out.println(result);
วิธีที่ 5: ใช้ Stream API (Java 8+)
String result = Arrays.stream(stringArray)
.collect(Collectors.joining(" "));
การเปรียบเทียบ
| วิธี | Java Version | Delimiter Support | Prefix/Suffix | คะแนน |
|---|---|---|---|---|
| StringBuffer loop | 1.0 | Manual | Manual | ⭐⭐ |
| Arrays.toString() | 1.5 | Fixed ([, , ]) | Fixed | ⭐ (wrong use) |
| StringJoiner | 8 | ✓ | ✓ (setPrefix/setSuffix) | ⭐⭐⭐⭐ |
| String.join() | 8 | ✓ | ✗ | ⭐⭐⭐⭐⭐ |
| Stream + Collectors.joining | 8 | ✓ | ✓ | ⭐⭐⭐⭐ |
ตัวอย่าง StringJoiner ขั้นสูง
StringJoiner joiner = new StringJoiner(", ", "[", "]"); // delimiter, prefix, suffix
joiner.add("Apple").add("Banana").add("Cherry");
System.out.println(joiner); // [Apple, Banana, Cherry]
สรุปแนะนำ
- Simple join:
String.join(delimiter, array) - Need prefix/suffix:
new StringJoiner(delimiter, prefix, suffix) - From Stream/Collection:
stream.collect(Collectors.joining(delimiter)) - Legacy Java < 8: StringBuilder loop