![]() |
VOOZH | about |
Given a list of characters. In this article, we will write a Java program to convert the given list to a string.
Input : list = {'g', 'e', 'e', 'k', 's'}
Output : "geeks"
Input : list = {'a', 'b', 'c'}
Output : "abc"
Strings - Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well.
List - List in Java implements the ability to manage the ordered collection. It comprises index-based techniques to insert, update, delete, and search the elements of the list. It can have duplicate elements also. The List interface is located in java.util package and inherits the Collection interface.
There are numerous approaches to convert the List of Characters to String in Java. These are -
- Using StringBuilder class
- Using join() method of Joiner class
- Using List.toString(), String.substring() and String.replaceAll() method
- Using Collectors
A simple solution would be to iterate through the list and create a new string with the help of the StringBuilder class, as shown below:
List - [G, e, e, k, s] String - Geeks
Time Complexity: O(n)
Auxiliary Space: O(n)
A joiner class can be used to join pieces to text specified as an array and return the results as a string. This method is also called the Guava method.
Output
List - [G, e, e, k] String - Geek
Time Complexity: O(n)
Auxiliary Space: O(n)
The toString() method on a list returns a string that is surrounded by square brackets and has commas between items. The idea is to get rid of square brackets using the substring() method and comma and space replace using the replaceAll() method.
List - [G, e, e, k] String - Geek
Time Complexity: O(n)
Auxiliary Space: O(n)
In Java 8, we can make use of stream API with Java collectors.
List - [G, e, e, k] String - Geek
Time Complexity: O(n)
Auxiliary Space: O(n)