Java program to convert a list of characters into a string

Java 8Object Oriented ProgrammingProgramming

A list of characters can be converted into a string by iterating through the list of characters and using a StringBuilder class to create a string.

A program that demonstrates this is given as follows.

Example

Live Demo

import java.util.Arrays;
import java.util.List;
public class Example {
   public static void main(String[] args) {
      List<Character> cList =  Arrays.asList('B', 'e', 'a', 'u', 't', 'y');
      StringBuilder sb = new StringBuilder();
      for (Character c : cList) {
         sb.append(c);
      }
      String str = sb.toString(); 
      System.out.println("The string obtained is: " + str);
   }
}

Output

The string obtained is: Beauty

Now let us understand the above program.

First, the character list is specified. Then the StringBuilder class is used to create a string by iterating through the list of characters and appending them. Finally, the string str is displayed. The code snippet that demonstrates this is given as follows −

List<Character> cList =  Arrays.asList('B', 'e', 'a', 'u', 't', 'y');
StringBuilder sb = new StringBuilder();
for (Character c : cList) {
   sb.append(c);
}
String str = sb.toString(); 
System.out.println("The string obtained is: " + str);
raja
Published on 05-Dec-2018 16:23:22
Advertisements