Как преобразовать arraylist в string java
In Java, as we all know ArrayList class is derived from the List interface. Here we are given an ArrayList of strings and the task is to convert the ArrayList to a string array.
Illustration:
Methods:
- Using get() method of ArrayList class
- Using toArray() method of ArrayList class
- Using copyOf() method of Arrays class
Method 1: Using ArrayList.get() Method of ArrayList class
Syntax:
Approach:
- Get the ArrayList of Strings.
- Find the size of ArrayList using size() method, and Create a String Array of this size.
- Fetch each element of the ArrayList one by one using get() method.
- Assigned each element into String Array using assignment(=) operator.
- Printing string array.
Example:
Method 2: Using toArray() method of ArrayList class
Here we will be creating an object array to store elements received from ArrayList by creating an array of strings.
Преобразование списка в строку Java
В этом посте мы обсудим, как преобразовать список в строку в Java. Решение должно объединять элементы предоставленного списка в одну строку с заданным разделителем. Решение не должно добавлять разделитель до или после списка.
1. Использование StringBuilder
Идея состоит в том, чтобы пройтись по списку и объединить каждый элемент списка с StringBuilder экземпляр с указанным разделителем. Наконец, мы возвращаем строковое представление StringBuilder . Обратите внимание, что решение должно иметь дело с завершающими символами разделителей.
Java ArrayList toString()
The Java ArrayList toString() method converts an arraylist into a String.
The syntax of the toString() method is:
Here, arraylist is an object of the ArrayList class.
toString() Parameters
The toString() method doesn’t take any parameters.
toString() Return Values
- returns a string representation of the arraylist
Example: Convert ArrayList to String
Output
In the above example, we have created an arraylist named languages . Notice the line,
Here, we have used the toString() method to convert the arraylist into a string. The method converts the entire arraylist into a single String .
Note: The ArrayList class does not have its own toString() method. Rather it overrides the method from the Object class.
Java List to String
We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List.We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.
Example:
OUTPUT:
Using + operator
This is not an efficient way so, normally avoid it.We use concate( + ) operator to add one by one element from array inside loop and assign it into String.
Example:
OUTPUT:
Using String’s join method in java 8
String’s join method is introduced in Java 8 . This method is very handy to create delimited separated String from list.
This approach will work only for List of String. In case, if you have list of Double, then you can use java 8‘s Collectors to join the String.
Here is an example:
Output:
As you can see, we have used Collectors.joining(",") to join elements of String by ,
Using Apache common lang3
You can also use Apache common’s StringUtils to convert list to String.
Here is the dependency which you need to add for Apache common lang3 in pom.xml .
Here is the example:
Using Guava library
You can also use Guava’s Joiner class to convert list to String.
Here is the dependency which you need to add for guava in pom.xml .
Here is the example:
As you can see, we have used com.google.common.base.Joiner class to join elements of String by *
Print elements of list as String
Sometimes, we just need to print elements of the list. We can simply use toString() method
Let’s understand with the help of example.
Output:
Did you notice we did not even call toString() method on intList object?
JVM internally calls toString() method of type of element within this list. In this case, we have list of Integers, so it will call Integer’s toString() method.