- How to convert an array to a string in Java
- You might also like.
- How to print array in java
- Using Arrays.toString()
- Using deepToString() method
- Using Java 8 Stream API
- Using for loop
- Using for-each loop
- Print array in reverse order in java
- Print array with custom objects
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Create Array from 1 to n in Java
- How to Print 2D Array in Java
- Return Empty Array in Java
- How to Write Array to File in Java
- How to Initialize an Array with 0 in Java
- Set an Array Equal to Another Array in Java
- Преобразование массива в строку в Java
- Преобразование массива в строку с помощью метода Arrays.toString() в Java
- Преобразование массива в строку с помощью метода String.join() в Java
- Преобразование массива в строку с помощью метода Arrays.stream() в Java
- Сопутствующая статья — Java Array
- Сопутствующая статья — Java String
How to convert an array to a string in Java
Sometimes you want to convert an array of strings or integers into a single string. However, unfortunately, there is no direct way to perform this conversion in Java.
The default implementation of the toString() method on an array only tells us about the object’s type and hash code and returns something like [Ljava.lang.String;@f6f4d33 as output.
In this article, we shall look at different ways to convert an array into a string in Java.
The String.join() method returns a new string composed of a set of elements joined together using the specified delimiter:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = String.join(", ", fruits); System.out.println(str); // Apple, Orange, Mango, Banana
You can also pass the strings that you want to join directly to the String.join() method, as shown below:
String str = String.join(" ", "Java", "is", "awesome", "🌟"); System.out.println(str); // Java is awesome 🌟
ListString> animals = List.of("Fox", "Dog", "Loin", "Cow"); String str = String.join("-", animals); System.out.println(str); // Fox-Dog-Loin-Cow CharSequence[] vowels = "a", "e", "i", "o", "u">; String str2 = String.join(",", vowels); System.out.println(str2); // a,e,i,o,u
Java Streams API provides the Collectors.joining() method to join strings from the Stream using a delimiter:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.stream(fruits).collect(Collectors.joining(", ")); System.out.println(str); // Apple, Orange, Mango, Banana
Besides delimiter, you can also pass prefix and suffix of your choice to the Collectors.joining() method:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.stream(fruits) .collect(Collectors.joining(", ", "[", "]")); System.out.println(str); // [Apple, Orange, Mango, Banana]
The Arrays.toString() method returns a string representation of the contents of the specified array. All array’s elements are joined together using a comma ( , ) as a delimiter and enclosed in square brackets ( [] ) as shown below:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.toString(fruits); System.out.println(str); // [Apple, Orange, Mango, Banana]
The best thing about Arrays.toString() is that it accepts both primitive and object arrays and converts them into a string:
int[] number = 1, 2, 3, 4>; System.out.println(Arrays.toString(number)); // [1, 2, 3, 4] double[] prices = 3.46, 9.89, 4.0, 2.89>; System.out.println(Arrays.toString(prices)); // [3.46, 9.89, 4.0, 2.89]
The StringBuilder class is used to create mutable strings in Java. It provides an append() method to append the specified string to the sequence. The toString() method of the StringBuilder class returns a string representation of the data appended. To convert an array to a string using StringBuilder , we have to use a loop to iterate over all array’s elements and then call the append() method to append them into the sequence:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; StringBuilder builder = new StringBuilder(); for (int i = 0; i fruits.length; i++) builder.append(fruits[i]).append(" "); > String str = builder.toString(); System.out.println(str); // Apple Orange Mango Banana
int[] number = 1, 2, 3, 4>; StringBuilder builder = new StringBuilder(); for (int i = 0; i number.length; i++) builder.append(number[i]).append(" "); > String str = builder.toString(); System.out.println(str); // 1 2 3 4
The StringJoiner class was introduced in Java 8, and it provides methods for combining multiple strings into a single string using the specified delimiter:
String path = new StringJoiner("/") .add("/usr") .add("share") .add("projects") .add("java11") .add("examples").toString(); System.out.println(path); // /usr/share/projects/java11/examples
As you can see above, the StringJoiner class provides a very fluent way of joining strings. We can easily chain multiple calls together to build a string.
Finally, the last way to convert an array of strings into a single string is the Apache Commons Lang library. The join() method of the StringUtils class from Commons Lang transforms an array of strings into a single string:
String[] names = "Atta", "Arif", "Meero", "Alex">; String str = StringUtils.join(names, "|"); System.out.println(str); // Atta|Arif|Meero|Alex
To convert a string back into an array in Java, read this article. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
How to print array in java
In this post, we will see how to print array in java.
There are multiple ways to print an array. Let’s go through few ways to print array in java.
Using Arrays.toString()
You can use Arrays.toString() method to print array in java. This is simplest ways to print an array.
Arrays.toString() returns string object.This String contains array in string format.
Let us understand with the code
Using deepToString() method
Basically Arrays.toString() works fine for a 1-dimensional arrays,but it won’t work for multidimensional arrays.
Let’s say we have 2-dimensional array as shown
1 2 3
4 5 6
7 8 9
To convert multidimensional arrays to string, you can use Arrays.deepToString() method. This is how you can print 2D array in java.
Using Java 8 Stream API
In java 8, you can convert array to Stream and print array with Stream’s foreach() method.
Arrays . stream ( string2DArray ) . flatMap ( str — > Arrays . stream ( str ) ) . forEach ( System . out : : println ) ;
Arrays . stream ( int2DArray ) . flatMapToInt ( i — > Arrays . stream ( i ) ) . forEach ( System . out : : println ) ;
As you can see we have seen how to print String array and Integer array in java using Stream.
Using for loop
You can iterate the array using for loop and print elements of array in java.
Using for-each loop
For each works same as for loop but with differs syntax.
Print array in reverse order in java
You can iterate the array using for loop in reverse order and print the element. This will print array in reverse order.
Print array with custom objects
In case, you have custom object in the array, then you should override toString() method in custom class, else it will give you unexpected results.
Let’s see with the help of example
Create a simple class named Color.java
Create main class named PrintArrayOfColors.java
If you notice, we don’t have toString() method in Color class, that’s why it is calling Object’s toString() method and we are not able to see meaningful results.
We need to override toString() method in Color class and we will get informative output.
When you run PrintListOfColorsMain again, you will get below output:
As you can see, we have much meaningful output now.
That’s all about how to print array in java.
Was this post helpful?
Share this
Next Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers
Related Posts
Author
Related Posts
Create Array from 1 to n in Java
Table of ContentsIntroductionArray in JavaCreate Array from 1 to N in JavaUsing Simple For loop in JavaUsing IntStream.range() method of Stream API in JavaUsing IntStream.rangeClosed() method of Stream API in JavaUsing IntStream.iterate() method of Stream API in JavaUsing the Stream class of Stream API in JavaUsing Arrays.setAll() method in JavaUsing Eclipse Collections Framework in JavaUsing […]
How to Print 2D Array in Java
Table of ContentsIntroductionWhat is a 2-dimensional array or matrix in java?How to print a 2D array in java?Simple Traversal using for and while loopUsing For-Each Loop to print 2D Array in JavaArrays.toString() method to print 2D Array in JavaArrays.deepToString() method to print 2D Array in JavaUsing Stream API in Java 8 to print a 2D […]
Return Empty Array in Java
Table of ContentsWhat Is the Need to Return an Empty Array?How Do You Return Empty Array in Java?Using Curly Braces to Return Empty Array in JavaUsing Anonymous Array Objects – New Int[0] to Return Empty Array Using Empty Array Declaration to Return Empty Array in JavaUsing Apache Commons Library – Array Utils Package to Return Empty […]
How to Write Array to File in Java
Table of ContentsWays to Write Array to File in JavaUsing BufferWriterUsing ObjectOutputStream In this post, we will see how to write array to file in java. Ways to Write Array to File in Java There are different ways to write array to file in java. Let’s go through them. Using BufferWriter Here are steps to […]
How to Initialize an Array with 0 in Java
Table of ContentsArraysInitializing Newly Created ArrayUsing Default Initialization of Arrays in JavaUsing Initialization After DeclarationUsing Simultaneous Initializing and Declaration of ArrayUsing Reflection in JavaInitializing Existing ArrayUsing the Arrays.fill() Function of JavaUsing the for LoopUsing Reassignment From Another ArrayUsing Collections.nCopies() Function of JavaInitializing User-Defined Object ArrayConclusion This article discusses the arrays and different ways to initialize […]
Set an Array Equal to Another Array in Java
Table of ContentsSetting an Array Variable Equal to Another Array VariableSet an Array Equal to Another Array in Java Using the clone() MethodSet an Array Equal to Another Array in Java Using the arraycopy() MethodSet an Array Equal to Another Array in Java Using the copyOf() MethodSet an Array Equal to Another Array in Java […]
Преобразование массива в строку в Java
- Преобразование массива в строку с помощью метода Arrays.toString() в Java
- Преобразование массива в строку с помощью метода String.join() в Java
- Преобразование массива в строку с помощью метода Arrays.stream() в Java
В этом руководстве мы увидим, как преобразовать массив в строку различными способами в Java. Массив состоит из элементов одного типа данных, а строка — это просто набор символов. В следующих примерах мы рассмотрим три метода преобразования массива в строку.
Преобразование массива в строку с помощью метода Arrays.toString() в Java
Arrays — это класс, содержащий различные статические методы, которые могут управлять массивами. Одна из полезных функций Arrays — это toString (), которая принимает массив различных типов данных, таких как int и char, и возвращает строковое представление массива.
В этом примере мы создаем массив arrayOfInts типа int и заполняем его несколькими элементами. Чтобы преобразовать arrayOfInts в строку, мы используем Arrays.toString() и передаем его в качестве аргумента, возвращающего строку arrayToString , которую мы печатаем в выводе.
import java.util.Arrays; public class ArrayToString public static void main(String[] args) int[] arrayOfInts = 1, 3, 9, 11, 13>; String arrayToString = Arrays.toString(arrayOfInts); System.out.println(arrayToString); > >
Преобразование массива в строку с помощью метода String.join() в Java
Метод join() был добавлен в класс String с выпуском JDK 8. Эта функция возвращает строку, объединенную с указанным разделителем. join() принимает разделитель и элементы в качестве аргументов.
В коде есть массив типа String . Мы вызываем метод String.join() и передаем пробел в качестве разделителя, а также массив, элементы которого будут объединены пробелом.
Вывод показывает все элементы массива, разделенные пробелами.
public class ArrayToString public static void main(String[] args) String[] arrayOfStrings = "One", "Two", "Three", "four", "Five">; String arrayToString = String.join(" ", arrayOfStrings); System.out.println(arrayToString); > >
Преобразование массива в строку с помощью метода Arrays.stream() в Java
В этом примере мы используем Stream API, представленный в JDK 8. Arrays.stream() принимает массив. Метод collect() возвращает результат после выполнения указанной операции над каждым элементом массива. Здесь мы выполняем операцию Collectors.joining() над элементами массива, которая собирает элементы и объединяет их для возврата в виде целой строки.
import java.util.Arrays; import java.util.stream.Collectors; public class ArrayToString public static void main(String[] args) String[] arrayOfStrings = "One", "Two", "Three", "four", "Five">; String arrayToString = Arrays.stream(arrayOfStrings).collect(Collectors.joining()); System.out.println(arrayToString); > >
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Сопутствующая статья — Java Array
Сопутствующая статья — Java String
Copyright © 2023. All right reserved