杰瑞科技汇

Java中array如何join成字符串?

Of course! In Java, there isn't a single built-in function called array.join() like in some other languages (e.g., JavaScript). However, there are several excellent and standard ways to join the elements of an array into a single string.

Java中array如何join成字符串?-图1
(图片来源网络,侵删)

Here are the most common and recommended methods, from the most modern to the classic approach.


Using String.join() (Modern & Recommended - Java 8+)

This is the cleanest and most straightforward method if you are using Java 8 or newer. It's designed specifically for this purpose.

How it works: You provide a delimiter (the string to put between elements) and an array (or any Iterable like a List) of strings.

Example:

import java.util.Arrays;
public class ArrayJoinExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
        // Join the array elements with a comma and a space
        String result = String.join(", ", fruits);
        System.out.println(result);
        // Output: Apple, Banana, Cherry, Date
    }
}

Key Points:

  • Requirement: The array elements must be strings. If your array contains non-String objects (like Integer or custom objects), you must first convert them to strings.
  • Flexibility: You can also use it with Lists:
    java.util.List<String> fruitList = Arrays.asList("Apple", "Banana", "Cherry");
    String resultFromList = String.join(" - ", fruitList);
    System.out.println(resultFromList);
    // Output: Apple - Banana - Cherry

Using String.join() with a Stream (For Non-String Arrays)

If your array contains non-string objects (e.g., Integer, Double, or your own class), you can use a Stream to convert each element to a string before joining.

How it works: Convert the array to a stream, map each element to its string representation, and then collect the results using Collectors.joining().

Example:

import java.util.Arrays;
import java.util.stream.Collectors;
public class ArrayJoinNonStringExample {
    public static void main(String[] args) {
        Integer[] numbers = {10, 20, 30, 40, 50};
        // Convert each Integer to a String, then join them
        String result = Arrays.stream(numbers) // 1. Create a stream from the array
                              .map(Object::toString) // 2. Convert each element to a String
                              .collect(Collectors.joining(" | ")); // 3. Join with the delimiter
        System.out.println(result);
        // Output: 10 | 20 | 30 | 40 | 50
    }
}

Key Points:

  • This is the standard, modern way to handle arrays of any object type.
  • Object::toString is a method reference that is equivalent to x -> x.toString(). It's a clean way to call the toString() method on every element.

Using Arrays.toString() (For Debugging)

This method is useful for getting a quick, debug-friendly string representation of an array. It is not for creating custom-formatted strings.

How it works: It automatically adds square brackets [] and a comma and space as delimiters.

Example:

import java.util.Arrays;
public class ArraysToStringExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry"};
        int[] numbers = {1, 2, 3};
        System.out.println(Arrays.toString(fruits));
        // Output: [Apple, Banana, Cherry]
        System.out.println(Arrays.toString(numbers));
        // Output: [1, 2, 3]
    }
}

Key Points:

  • Not for custom formatting: You cannot change the delimiter or the brackets. Its primary purpose is for logging and debugging.
  • Works for any type of array (primitive or object).

Using a StringBuilder (Classic & Performant)

This is the traditional way to build strings in a loop. It's highly performant, especially for large arrays, because it avoids creating many intermediate string objects.

How it works: Loop through the array, append each element to a StringBuilder, and add the delimiter after each element (except the last one).

Example:

import java.util.Arrays;
public class StringBuilderJoinExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fruits.length; i++) {
            // Append the element
            sb.append(fruits[i]);
            // Append the delimiter if it's not the last element
            if (i < fruits.length - 1) {
                sb.append(", ");
            }
        }
        String result = sb.toString();
        System.out.println(result);
        // Output: Apple, Banana, Cherry, Date
    }
}

Key Points:

  • Performance: Excellent for very large arrays or in performance-critical code.
  • Control: Gives you full control over the joining logic.
  • Boilerplate: Requires more code than the String.join() methods.

Summary & Comparison

Method When to Use Pros Cons
String.join() Your default choice. When you have an array of strings and are using Java 8+. Very clean, readable, and concise. Only works for arrays of strings.
Stream + Collectors.joining() When you have an array of non-string objects. Modern, flexible, handles any object type. Slightly more verbose than String.join().
Arrays.toString() For debugging or logging. Not for creating user-facing strings. Extremely simple, one-line call. Not customizable (fixed brackets and delimiter).
StringBuilder In performance-critical applications or when you need custom logic not covered by other methods. Best performance, full control. More verbose and manual.

Final Recommendation

For most everyday use cases in modern Java (version 8+):

  1. If your array contains strings, use String.join().
  2. If your array contains any other type of object, use Arrays.stream().map().collect(Collectors.joining()).
分享:
扫描分享到社交APP
上一篇
下一篇