Java
string manipulation
delimited strings
programming
coding tips

What's the best way to build a string of delimited items in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Building a string of delimited items is common in Java programming, especially when dealing with data serialization or output formatting. There are several methods in Java to create such strings, each with its own benefits and drawbacks. This article explores some popular strategies for building delimited strings.

1. Using StringBuilder

The StringBuilder class is ideal for constructing strings when intermediate modifications are necessary. It is mutable, which means its content can be changed without creating new objects. Here's an example using StringBuilder to create a comma-separated list:

java
1import java.util.List;
2
3public class StringBuilderExample {
4    public static String buildDelimitedString(List<String> items, String delimiter) {
5        StringBuilder sb = new StringBuilder();
6        for (int i = 0; i < items.size(); i++) {
7            sb.append(items.get(i));
8            if (i < items.size() - 1) {
9                sb.append(delimiter);
10            }
11        }
12        return sb.toString();
13    }
14
15    public static void main(String[] args) {
16        List<String> items = List.of("apple", "banana", "cherry");
17        System.out.println(buildDelimitedString(items, ","));
18    }
19}

Pros:

  • Efficient for constructing strings with many concatenation operations.
  • More memory efficient than concatenating with + operator.

Cons:

  • Requires explicit handling of delimiters between items.
  • Code can be slightly more verbose.

2. Using String.join (Java 8 and above)

Java 8 introduced a convenient String.join method to handle delimited strings, making the process more readable and concise.

java
1import java.util.List;
2
3public class StringJoinExample {
4    public static void main(String[] args) {
5        List<String> items = List.of("apple", "banana", "cherry");
6        String result = String.join(",", items);
7        System.out.println(result);
8    }
9}

Pros:

  • Simplified syntax and improved readability.
  • Automatically handles the delimiter between items.

Cons:

  • Limited to joining collections of strings or an array of strings directly.
  • Available only in Java 8 and above.

3. Using Collectors.joining with Streams

Streams and the Collectors.joining() method offer a more functional approach. This is especially useful when additional transformation or filtering is required before joining.

java
1import java.util.List;
2import java.util.stream.Collectors;
3
4public class StreamJoiningExample {
5    public static void main(String[] args) {
6        List<String> items = List.of("apple", "banana", "cherry");
7        String result = items.stream()
8                             .collect(Collectors.joining(","));
9        System.out.println(result);
10    }
11}

Pros:

  • Integrates seamlessly with the Stream API for more complex operations.
  • Supports filtering and mapping operations before joining.

Cons:

  • Can be overkill for simple joining tasks without additional stream operations.
  • May be less intuitive for those unfamiliar with Java Streams.

4. Handling Edge Cases

When building delimited strings, it's crucial to handle cases like null values and empty collections. These can be addressed by using the Objects class or Stream filters.

java
1import java.util.List;
2import java.util.stream.Collectors;
3
4public class HandleEdgeCasesExample {
5    public static void main(String[] args) {
6        List<String> items = List.of("apple", null, "cherry", "");
7        String result = items.stream()
8                             .filter(item -> item != null && !item.isEmpty())
9                             .collect(Collectors.joining(","));
10        System.out.println(result);
11    }
12}

Considerations:

  • Be aware of null pointer exceptions when using String.join or Collectors.joining.
  • Empty or null elements can be filtered out before joining, as shown.

5. Performance Comparison

MethodJava VersionReadabilityPerformanceUse Cases
StringBuilderAllModerateHighBest for performance-critical applications with high concatenation operations.
String.join8 and aboveHighModerateIdeal for simple concatenation of strings in a collection.
Collectors.joining8 and aboveHighModerateSuitable for when additional transformations or filtering are required.

Conclusion

Choosing the best method to build a string of delimited items in Java largely depends on the specific requirements and context of your application. StringBuilder remains a powerful tool for performance, whereas String.join and Streams provide readability and functional paradigms. By considering the nature of your data and the operational requirements, you can choose the most suitable method for your needs.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions