SoFunction
Updated on 2025-03-08

Summary of four ways to convert arrays into strings in Java

1. Use  ()

For one-dimensional arrays, you can useIn the classtoString()method:

import ;

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        String result = (nums);
        (result); // Output: [1, 2, 3, 4, 5]    }
}

2. Use  ()

For multidimensional arrays, usedeepToString()method:

import ;

public class Main {
    public static void main(String[] args) {
        int[][] nums = {{1, 2, 3}, {4, 5, 6}};
        String result = (nums);
        (result); // Output: [[1, 2, 3], [4, 5, 6]]    }
}

3. Use StringBuilder

If you want to customize the string format, you can useStringBuilderManually build strings:

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        StringBuilder sb = new StringBuilder();
        for (int num : nums) {
            (num).append(", ");
        }
        // Delete the last ", "        if (() > 0) {
            (() - 2);
        }
        String result = ();
        (result); // Output: 1, 2, 3, 4, 5    }
}

4. Use Stream API (Java 8 and above)

If you are using Java 8 or later, you can take advantage of the Stream API:

import ;

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        String result = (nums)
                              .mapToObj(String::valueOf)
                              .reduce((a, b) -> a + ", " + b)
                              .orElse("");
        (result); // Output: 1, 2, 3, 4, 5    }
}

Summarize

Choose the method that suits your needs to convert the array to a string. For simple cases,()is the most convenient, and if you need a custom format,StringBuilderorStreamThe API may be more suitable.

Knowledge points:

kind

StringBuilderis a class in Java that is specifically used to create and manipulate mutable strings. andStringDifferent categories,StringBuilderAllows modifying strings without generating new string objects. This makes it more efficient when string modifications are required. The following isStringBuilderMain features and usages:

Main features

  • Variability
    • StringBuilderThe content of  can be modified and no new objects are created. This improves performance when splicing multiple strings.
  • performance
    • becauseStringBuilderIts internal character array is only expanded when needed, so when doing a lot of string operations, it is usually better thanStringMore efficient.
  • Thread safety
    • StringBuilderIt is non-thread-safe. If multiple threads access the same one at the same timeStringBuilderObjects, may cause data inconsistency. In a multi-threaded environment, it should be usedStringBuffer, it is thread-safe.

Common methods

  • Construction method
    • StringBuilder(): Create an empty oneStringBuilder
    • StringBuilder(String str): Initialize with the specified string.
  • Add content
    • append(String str): Add a string at the end of the current string.
    • append(int i): Add integer at the end.
    • append(char c): Add characters at the end.
  • Insert content
    • insert(int offset, String str): Insert a string at the specified location.(Insert before index)
  • Delete content
    • delete(int start, int end): Delete content from the specified start position to the end position.(Not before and after)
    • deleteCharAt(int index): Delete the character of the specified index.
  • Replace content
    • replace(int start, int end, String str): Replace content from start to end with the specified string.(Not before and after)
  • Convert to string
    • toString():WillStringBuilderConvert the content toString

Sample code

public class StringBuilderExample {
    public static void main(String[] args) {
        // Create a StringBuilder object        StringBuilder sb = new StringBuilder();

        // Add string        ("Hello");
        (", ");
        ("World!");

        // Output: Hello, World!        (());

        // Insert string        (5, " Java");
        // Output: Hello Java, World!        (());

        // Delete some content        (5, 10);
        // Output: Hello, World!        (());

        // Replace content        (0, 5, "Hi");
        // Output: Hi, World!        (());
    }
}

Summarize

StringBuilderIt is a very practical tool when processing strings, especially in scenarios where strings need to be frequently modified and spliced. Due to its variability and efficiency,StringBuilderOften recommended for performance-sensitive string operations.

2. Conversion through streams

This code uses Java 8's Stream API to convert an array of integersnumsConvert to a comma-separated string. Here is a detailed explanation of each section:

Code decomposition

String result = (nums)
                      .mapToObj(String::valueOf)
                      .reduce((a, b) -> a + ", " + b)
                      .orElse("");
  • (nums)
    • Array of integersnumsConvert to a stream. Stream is an abstraction used to process collections, which can perform various operations such as filtering, mapping, and reduction.
  • .mapToObj(String::valueOf)
    • mapToObjis an intermediate operation used to transfer basic types of streams (such asintStream) converts to object stream. Here, it converts each integer into the corresponding string.
    • String::valueOfis a method reference, equivalent tonum -> (num). This operation willnumsEach integer in it is converted to a string.
  • .reduce((a, b) -> a + ", " + b)
    • reduceis a terminal operation that combines elements in the stream. Here, it accepts a binary operator that combines two strings.
    • (a, b) -> a + ", " + bIndicates that two strings are concatenated with commas and spaces.aandbThe previous and current strings in the stream respectively.
    • This operation combines all strings in the stream into a string to form a comma-separated list.
  • .orElse("")
    • orElseis the default value when the stream is empty. ifreduceThe result is()(For example, if the input array is empty), an empty string is returned.""
    • This can avoid the occurrence of during the conversion process.NullPointerException, make sure the result is always a valid string.

Example

Assumptionnumsyes[1, 2, 3], Here are the results of each step:

  • Creation of streams(nums)Generate a stream with the content of1, 2, 3
  • Convert to stringmapToObj(String::valueOf)Generate a string stream with the content of"1", "2", "3"
  • Merge stringsreduceMerge the generated string into"1, 2, 3"
  • Processing empty:ifnumsis an empty array.orElse("")Will ensure that the result is""Instead ofnull

Summarize

This code uses Java 8's Stream API and functional programming features to efficiently convert an array of integers into a formatted string. Its structure is clear, and the operation of streams makes the code more concise and readable.

This is the end of this article about the four methods of converting Java arrays into strings. For more related contents of converting Java arrays into strings, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!