Table of Contents
Trong bài này chúng ta cùng xem một số cách cộng chuỗi (string concat/ joiner) trong Java và tính năng mới StringJoiner trong Java 8.
1. Sử dụng StringBuilder/ StringBuffer
Trước Java 8, để có thể ghép các chuỗi với một dấu phân cách, thường chúng ta phải lặp qua các phần tử của một mảng hoặc danh sách và sử dụng StringBuilder/ StringBuffer để lưu giữ.
Ví dụ:
final String DELIMITER = ", ";
String[] arr = { "one", "two", "three" };
int numOfElements = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numOfElements; i++) {
sb.append(arr[i]);
if (i < numOfElements - 1) {
sb.append(DELIMITER);
}
}
System.out.println(sb.toString()); // one, two, three
[/code]
<!-- /wp:shortcode -->
<!-- wp:heading -->
<h2>2. Sử dụng StringJoiner trong Java 8</h2>
<!-- /wp:heading -->
<!-- wp:paragraph -->
<p>Java 8 đã thêm một lớp final <strong>StringJoiner</strong> trong gói <strong>java.util</strong>. Nó được sử dụng để xây dựng một chuỗi ký tự được phân tách bằng dấu phân cách như dấu phẩy (,), dấu nối (-), …. Bạn cũng có thể chuyển tiền tố (prefix) và hậu tố (suffix) vào chuỗi.</p>
<!-- /wp:paragraph -->
<!-- wp:heading {"level":3} -->
<h3>2.1. Ví dụ StringJoiner với dấu phân tách (delimiter)</h3>
<!-- /wp:heading -->
<!-- wp:shortcode -->
StringJoiner stringJoiner = new StringJoiner(", ");
stringJoiner.add("one");
stringJoiner.add("two");
stringJoiner.add("three");
System.out.println(stringJoiner.toString()); // one, two, three
2.2. Ví dụ StringJoiner với tiền tố (prefix) và hậu tố (suffix)
StringJoiner stringJoinerWithPrefixSufix = new StringJoiner(",", "{", "}");
stringJoinerWithPrefixSufix.add("1");
stringJoinerWithPrefixSufix.add("2");
stringJoinerWithPrefixSufix.add("3");
System.out.println(stringJoinerWithPrefixSufix.toString()); // {1,2,3}
2.3. Sử dụng phương thức static java.lang.String.join()
String strWithJoiner = String.join(", ", "one", "two", "three");
System.out.println(strWithJoiner); // one, two, three
List<String> list= Arrays.asList("one", "two", "three");
strWithJoiner = String.join(", ", list); // one, two, three
2.4. Sử dụng java.util.stream.Collectors.joining()
// joining with delimiter
List<String> list = Arrays.asList("one", "two", "three");
String collectorJoiningWithDelimiter = list.stream()
.map(element -> element)
.collect(Collectors.joining(", "));
System.out.println(collectorJoiningWithDelimiter); // one, two, three
// joining with prefix & suffix
String collectorJoiningWithPrefixSuffix = list.stream()
.map(element -> element)
.collect(Collectors.joining(", ", "{", "}"));
System.out.println(collectorJoiningWithPrefixSuffix); // {one, two, three}
3. Sử dụng thư viện Commons Lang
Nếu project của bạn không sử dụng phiên bản Java 8, các bạn cũng có thể sử dụng thư viện common-lang để thay thế. Thư viện này bao gồm rất nhiều phương thức tiện ích hỗ trợ giải quyết những thao tác với String, Number, ….
Thư viện common lang các bạn có thể download tại đây: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
String[] arr = { "one", "two", "three" };
String joinedString = StringUtils.join(arr, ", "); // one, two, three
List<String> list = Arrays.asList("one", "two", "three");
joinedString = StringUtils.join(list, ", "); // one, two, three
Related posts:
Java Program to Implement Ternary Search Tree
Extract network card address
Request a Delivery / Read Receipt in Javamail
Guava CharMatcher
Java Program to Implement Stack API
Java Program to Implement Unrolled Linked List
Prevent Cross-Site Scripting (XSS) in a Spring Application
Java String Conversions
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Phương thức forEach() trong java 8
Java Program to Perform integer Partition for a Specific Case
New Features in Java 14
Collect a Java Stream to an Immutable Collection
Guide to ThreadLocalRandom in Java
Java InputStream to String
Query Entities by Dates and Times with Spring Data JPA
Introduction to the Java NIO Selector
Mix plain text and HTML content in a mail
Java Program to Perform Polygon Containment Test
Java Program to Create a Random Graph Using Random Edge Generation
Các kiểu dữ liệu trong java
LinkedHashSet trong Java hoạt động như thế nào?
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Java Program to Perform the Shaker Sort
Hướng dẫn Java Design Pattern – Builder
Spring Security Login Page with React
Java Program to Find the Edge Connectivity of a Graph
Jackson vs Gson
Spring 5 and Servlet 4 – The PushBuilder
Java Program to Find the GCD and LCM of two Numbers
Java Program to Implement Horner Algorithm
Hướng dẫn Java Design Pattern – DAO