logo

Converter lista em string em Java

Às vezes, precisamos converter uma lista de caracteres em uma string. Uma string é uma sequência de caracteres, portanto podemos facilmente formar uma string a partir de uma matriz de caracteres. Temos algumas strings especiais, como uma string de palíndromo (uma string que é igual à string original depois de revertida). Para reverter uma string, precisamos converter a string em um array char para reverter todos os caracteres da string, e depois de reverter o array char, precisamos convertê-lo em uma string.

Em Java, temos várias maneiras pelas quais podemos converter uma lista em uma string:

1. Usando a classe StringBuilder

Temos uma maneira muito simples de converter uma lista em uma string, ou seja, usando o método StringBuilder aula. Iteramos a lista de char usando o loop for e geramos uma nova string com a ajuda do StringBuilder.

Vamos implementar o código para converter uma lista em uma string usando a classe StringBuilder:

ConvertListToStringExample1.java

 // import required classes and packages if any package javaTpoint.JavaExample; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // create class ConvertListToStringExample1 that will convert user given char list into a string class ConvertListToStringExample1 { // main() method start public static void main(String[] args) { // declare variables and list int size; String str; List charList = new ArrayList(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter size of char list.&apos;); size = sc.nextInt(); for(int i = 0; i <size; i++) { system.out.println('enter char['+i+']: '); charlist.add(sc.next().charat(0)); } close scanner class object sc.close(); display chrlist elements system.out.println('list: ' + charlist); create an of stringbuilder builder="new" stringbuilder(); iterate charlist and append each char to one by for (character ch : charlist) builder.append(ch); convert into string str="builder.toString();" system.out.println('string after converting list: str); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/39/convert-list-string-java.webp" alt="Convert List to String in Java"> <h3>2. Using Joiner class</h3> <p>Like <strong>StringBuilder</strong> , we have one more class, i.e., <strong>Joiner</strong> class, through which we can convert a list into a string. We use the <strong>join()</strong> method of the Joiner class, which is also known as the <strong>Guava</strong> method. The join() method joins the pieces into the specified text as an array and returns the results as a string.</p> <p>Let&apos;s implement the code for converting a list into a string by using the Joiner class:</p> <p>We are using the maven project, so it is required to add the following dependency in our POM.xml file.</p> <pre> com.google.guava guava r05 </pre> <p> <strong>ConvertListToStringExample2.java</strong> </p> <pre> // import required classes and packages if any import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.google.common.base.Joiner; // create class ConvertListToStringExample2 that will convert user given char list into a string using Joiner class class ConvertListToStringExample2 { // main() method start public static void main(String[] args) { // declare variables and list int size; String str; List charList = new ArrayList(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter size of char list.&apos;); size = sc.nextInt(); for(int i = 0; i <size; i++) { system.out.println('enter char['+i+']: '); charlist.add(sc.next().charat(0)); } close scanner class object sc.close(); display chrlist elements system.out.println('list: ' + charlist); convert list into string by using joiner str="Joiner.on(&apos;&apos;).join(charList);" system.out.println('string after converting list: str); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/39/convert-list-string-java-2.webp" alt="Convert List to String in Java"> <h3>3. Using List.toString(), String.substring() and String.replaceAll() methods</h3> <p>In 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:</p> <ol class="points"> <li>We use the toString() method of the list to convert the list into a string. The return string will also contain opening/closing square brackets and commas.</li> <li>We use the substring() method to get rid of opening/closing square brackets.</li> <li>We use the replaceAll() method to replace all the commas and spaces with blank or null.</li> </ol> <p>Let&apos;s implement the code for converting a list into a string by using the toString(), substring(), and replaceAll() methods:</p> <p> <strong>ConvertListToStringExample3.java</strong> </p> <pre> // import required classes and packages if any package javaTpoint.JavaExample; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // create class ConvertListToStringExample2 that will convert user given char list into a string using toString(), substring() and replaceAll() methods class ConvertListToStringExample3 { // main() method start public static void main(String[] args) { // declare variables and list int size; String str; List charList = new ArrayList(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter size of char list.&apos;); size = sc.nextInt(); for(int i = 0; i <size; 3 i++) { system.out.println('enter char['+i+']: '); charlist.add(sc.next().charat(0)); } close scanner class object sc.close(); display chrlist elements system.out.println('list: ' + charlist); convert list into string by using all the three methods of and str="charList.toString()" .substring(1, * charlist.size() - 1) .replaceall(', ', ''); system.out.println('string after converting list: str); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/39/convert-list-string-java-3.webp" alt="Convert List to String in Java"> <h3>4. Using Collectors in Java</h3> <p>It 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.</p> <p>Let&apos;s implement the code for converting a list into string by using the stream API with Collectors.</p> <p> <strong>ConvertListToStringExample3.java</strong> </p> <pre> // import required classes and packages if any import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; // create class ConvertListToStringExample4 that will convert user given char list into a string using Collectors class ConvertListToStringExample4 { // main() method start public static void main(String[] args) { // declare variables and list int size; String str; List charList = new ArrayList(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter size of char list.&apos;); size = sc.nextInt(); for(int i = 0; i <size; i++) { system.out.println('enter char['+i+']: '); charlist.add(sc.next().charat(0)); } close scanner class object sc.close(); display chrlist elements system.out.println('list: ' + charlist); convert list into string by using collect() and joining() methods str="charList.stream()" .map(string::valueof) .collect(collectors.joining()); system.out.println('string after converting list: str); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/39/convert-list-string-java-4.webp" alt="Convert List to String in Java"> <p>In all the above-discussed ways, we have frequently used the StringBuilder class for converting a list into a string. </p> <hr></size;></pre></size;></pre></size;></pre></size;>

ConvertListToStringExample2.java

 // import required classes and packages if any import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.google.common.base.Joiner; // create class ConvertListToStringExample2 that will convert user given char list into a string using Joiner class class ConvertListToStringExample2 { // main() method start public static void main(String[] args) { // declare variables and list int size; String str; List charList = new ArrayList(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter size of char list.&apos;); size = sc.nextInt(); for(int i = 0; i <size; i++) { system.out.println(\'enter char[\'+i+\']: \'); charlist.add(sc.next().charat(0)); } close scanner class object sc.close(); display chrlist elements system.out.println(\'list: \' + charlist); convert list into string by using joiner str="Joiner.on(&apos;&apos;).join(charList);" system.out.println(\'string after converting list: str); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/39/convert-list-string-java-2.webp" alt="Convert List to String in Java"> <h3>3. Using List.toString(), String.substring() and String.replaceAll() methods</h3> <p>In 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:</p> <ol class="points"> <li>We use the toString() method of the list to convert the list into a string. The return string will also contain opening/closing square brackets and commas.</li> <li>We use the substring() method to get rid of opening/closing square brackets.</li> <li>We use the replaceAll() method to replace all the commas and spaces with blank or null.</li> </ol> <p>Let&apos;s implement the code for converting a list into a string by using the toString(), substring(), and replaceAll() methods:</p> <p> <strong>ConvertListToStringExample3.java</strong> </p> <pre> // import required classes and packages if any package javaTpoint.JavaExample; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // create class ConvertListToStringExample2 that will convert user given char list into a string using toString(), substring() and replaceAll() methods class ConvertListToStringExample3 { // main() method start public static void main(String[] args) { // declare variables and list int size; String str; List charList = new ArrayList(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter size of char list.&apos;); size = sc.nextInt(); for(int i = 0; i <size; 3 i++) { system.out.println(\'enter char[\'+i+\']: \'); charlist.add(sc.next().charat(0)); } close scanner class object sc.close(); display chrlist elements system.out.println(\'list: \' + charlist); convert list into string by using all the three methods of and str="charList.toString()" .substring(1, * charlist.size() - 1) .replaceall(\', \', \'\'); system.out.println(\'string after converting list: str); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/39/convert-list-string-java-3.webp" alt="Convert List to String in Java"> <h3>4. Using Collectors in Java</h3> <p>It 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.</p> <p>Let&apos;s implement the code for converting a list into string by using the stream API with Collectors.</p> <p> <strong>ConvertListToStringExample3.java</strong> </p> <pre> // import required classes and packages if any import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; // create class ConvertListToStringExample4 that will convert user given char list into a string using Collectors class ConvertListToStringExample4 { // main() method start public static void main(String[] args) { // declare variables and list int size; String str; List charList = new ArrayList(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter size of char list.&apos;); size = sc.nextInt(); for(int i = 0; i <size; i++) { system.out.println(\'enter char[\'+i+\']: \'); charlist.add(sc.next().charat(0)); } close scanner class object sc.close(); display chrlist elements system.out.println(\'list: \' + charlist); convert list into string by using collect() and joining() methods str="charList.stream()" .map(string::valueof) .collect(collectors.joining()); system.out.println(\'string after converting list: str); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/39/convert-list-string-java-4.webp" alt="Convert List to String in Java"> <p>In all the above-discussed ways, we have frequently used the StringBuilder class for converting a list into a string. </p> <hr></size;></pre></size;></pre></size;>