logo

Convertir une liste en chaîne en Java

Parfois, nous devons convertir une liste de caractères en chaîne. Une chaîne est une séquence de caractères, nous pouvons donc facilement former une chaîne à partir d'un tableau de caractères. Nous avons des chaînes spéciales, comme une chaîne palindrome (une chaîne qui est la même que la chaîne d'origine après l'avoir inversée). Afin d'inverser une chaîne, nous devons convertir la chaîne en un tableau de caractères pour inverser tous les caractères de la chaîne, et après avoir inversé le tableau de caractères, nous devons le convertir en chaîne.

En Java, nous disposons de plusieurs façons de convertir une liste en chaîne :

1. Utilisation de la classe StringBuilder

Nous avons un moyen très simple de convertir une liste en chaîne, c'est-à-dire en utilisant le Générateur de chaînes classe. Nous parcourons la liste des caractères en utilisant la boucle for et générons une nouvelle chaîne à l'aide de StringBuilder.

Implémentons le code pour convertir une liste en chaîne en utilisant la 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;>