杰瑞科技汇

Java数组如何高效连接成字符串?

Of course! In Java, there isn't a single built-in join() method for arrays like there is in languages such as JavaScript or Python. However, there are several excellent and common ways to achieve this.

Java数组如何高效连接成字符串?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the best methods, from modern Java to classic approaches.

Summary of Methods

Method Best For... Pros Cons
String.join() (Java 8+) Most cases. Simple joining of an array of strings. Very concise, readable, and part of the standard library. Only works for arrays of String.
Collectors.joining() (Java 8+) Flexibility. Joining objects or custom formatting. Extremely powerful, works with any stream, allows prefixes/suffixes. More verbose if you just need a simple join.
Apache Commons Lang Legacy Projects. When you can't use Java 8+. Simple, consistent API for any array type. Requires an external library dependency.
Manual Loop (e.g., StringBuilder) Learning / No Dependencies. No dependencies, full control over the process. Verbose, more error-prone (e.g., off-by-one errors).

The Modern Java 8+ Way: String.join()

This is the simplest and most direct method, but it has one major limitation: it only works with arrays of String.

How it works:

You provide a delimiter and the String[] array. The method returns a new String with the elements joined.

Example:

public class StringJoinExample {
    public static void main(String[] args) {
        String[] fruits = { "Apple", "Banana", "Cherry" };
        // Join the array with a comma and a space as the delimiter
        String result = String.join(", ", fruits);
        System.out.println(result);
        // Output: Apple, Banana, Cherry
    }
}

Limitation:

If you try to use it with an array of a different type (like Integer), you'll get a compile-time error.

Java数组如何高效连接成字符串?-图2
(图片来源网络,侵删)
// This will NOT compile!
int[] numbers = {1, 2, 3};
// String numResult = String.join(", ", numbers); // Compile Error!

The Most Powerful Way: Collectors.joining() (with Streams)

This is the most flexible and recommended approach in modern Java (8+). It works with any type of array and allows for complex formatting.

How it works:

  1. Convert your array to a Stream using Arrays.stream().
  2. Use the map() operation to convert each element of the stream to a String (using String::valueOf or Object::toString).
  3. Collect the stream of strings into a single joined string using Collectors.joining().

Example: Joining an Array of Integers

This is a common use case where String.join() fails.

import java.util.Arrays;
import java.util.stream.Collectors;
public class StreamJoiningExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};
        String result = Arrays.stream(numbers) // 1. Create an IntStream
                              .mapToObj(String::valueOf) // 2. Convert each int to a String
                              .collect(Collectors.joining(", ")); // 3. Join them
        System.out.println(result);
        // Output: 10, 20, 30, 40
    }
}

Example: Joining an Array of Objects

This is extremely useful for custom objects.

import java.util.Arrays;
import java.util.stream.Collectors;
class User {
    private int id;
    private String name;
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    @Override
    public String toString() {
        return "User[id=" + id + ", name=" + name + "]";
    }
    public static void main(String[] args) {
        User[] users = {
            new User(1, "Alice"),
            new User(2, "Bob"),
            new User(3, "Charlie")
        };
        // Join with a custom delimiter and add brackets
        String userString = Arrays.stream(users)
                                  .map(User::toString) // Use the object's own toString method
                                  .collect(Collectors.joining(" | ", "[", "]"));
        System.out.println(userString);
        // Output: [User[id=1, name=Alice] | User[id=2, name=Bob] | User[id=3, name=Charlie]]
    }
}

The Classic Library Way: Apache Commons Lang

If you're working on a project that already uses the Apache Commons library, or if you're on a Java version older than 8, this is a great option. It's simple and works for any object array.

Java数组如何高效连接成字符串?-图3
(图片来源网络,侵删)

First, add the dependency:

Maven:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version> <!-- Use the latest version -->
</dependency>

Gradle:

implementation 'org.apache.commons:commons-lang3:3.14.0' // Use the latest version

How it works:

Use StringUtils.join() and pass the array and the delimiter.

Example:

import org.apache.commons.lang3.StringUtils;
public class ApacheCommonsExample {
    public static void main(String[] args) {
        // Works with String arrays
        String[] fruits = { "Apple", "Banana", "Cherry" };
        System.out.println(StringUtils.join(fruits, ", "));
        // Output: Apple, Banana, Cherry
        // Works with Integer arrays (autoboxing)
        Integer[] numbers = {10, 20, 30};
        System.out.println(StringUtils.join(numbers, " - "));
        // Output: 10 - 20 - 30
    }
}

The Manual Way: StringBuilder

This approach doesn't require any special libraries and is great for understanding the underlying mechanics. However, it's more verbose and requires careful handling to avoid adding a trailing delimiter.

How it works:

  1. Check if the array is empty or null.
  2. Create a StringBuilder.
  3. Loop through the array.
  4. Append the element.
  5. Append the delimiter, but only if it's not the last element.

Example:

public class StringBuilderExample {
    public static void main(String[] args) {
        String[] fruits = { "Apple", "Banana", "Cherry" };
        if (fruits == null || fruits.length == 0) {
            System.out.println("[]");
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("["); // Optional: add a prefix
        for (int i = 0; i < fruits.length; i++) {
            if (i > 0) {
                sb.append(", "); // Add delimiter before the next element
            }
            sb.append(fruits[i]);
        }
        sb.append("]"); // Optional: add a suffix
        String result = sb.toString();
        System.out.println(result);
        // Output: [Apple, Banana, Cherry]
    }
}

Which One Should You Use?

Your Situation Recommended Method
You are using Java 8+ and have a String[] String.join() - It's perfect.
You are using Java 8+ and have an array of objects, primitives, or need custom formatting Collectors.joining() - It's the most powerful and flexible.
You are on a Java version < 8 or your project already uses Apache Commons StringUtils.join() - Simple and effective.
You cannot use any external libraries and want to avoid streams StringBuilder - The classic, manual approach.
分享:
扫描分享到社交APP
上一篇
下一篇