Convert List to String in JavaSometimes, we need to convert a list of characters into a string. A string is a sequence of characters, so we can easily form a string from a character array. We have some special strings, such as a palindrome string (a string that is the same as the original string after reversing it). In order to reverse a string, we need to convert the string into a char array for reversing all the chars of string, and after reversing the char array, we need to convert it into a string. In Java, we have several ways through which we can convert a list into a string are as follows: 1. Using StringBuilder classWe have a very simple way to convert a list into a string, i.e., by using the StringBuilder class. We iterate the list of char using for loop and generate a new string with the help of StringBuilder. Let's implement the code for converting a list into a string by using the StringBuilder class: ConvertListToStringExample1.java Output: 2. Using Joiner classLike StringBuilder, we have one more class, i.e., Joiner class, through which we can convert a list into a string. We use the join() method of the Joiner class, which is also known as the Guava method. The join() method joins the pieces into the specified text as an array and returns the results as a string. Let's implement the code for converting a list into a string by using the Joiner class: We are using the maven project, so it is required to add the following dependency in our POM.xml file. ConvertListToStringExample2.java Output: 3. Using List.toString(), String.substring() and String.replaceAll() methodsIn this way of converting a list into a string, we use three methods of List and String classes. We use three methods to perform the following operations:
Let's implement the code for converting a list into a string by using the toString(), substring(), and replaceAll() methods: ConvertListToStringExample3.java Output: 4. Using Collectors in JavaIt is the last way to convert a list into a string. We use it rarely because here, we use stream API with collectors, which is available only in Java8. Let's implement the code for converting a list into string by using the stream API with Collectors. ConvertListToStringExample3.java Output: In all the above-discussed ways, we have frequently used the StringBuilder class for converting a list into a string. Next TopicList of Constants in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India