List to string joining java

Convert List to Concatenated String with Delimiter in Java

A quick guide to Learn Various ways of converting a List of Strings into a concatenated String Joined by a delimiter in Java. We will see different examples to join the String.

Convert Manually, With and Without Delimiter

Firstly, concatenate a string without any delimiter.

List words = Arrays.asList("Convert", "List", "of", "Strings", "To", "String"); String concatenatedString = ""; for(String word: words) < concatenatedString += word; >System.out.println(concatenatedString); Code language: Java (java)

As expected, the output is

ConvertListofStringsToString

Now, lets add a Delimiter. Remember, the delimiter should be appended at beginning of each word except the first one. We will add a space as a delimiter. However, you can use any character or a word as delimiter.

String concatenatedString = ""; String delimiter = " "; for (String word : words) < concatenatedString += concatenatedString.equals("") ? word : delimiter + word; > System.out.println(concatenatedString);Code language: Java (java)
Convert List of Strings To String

However, you should not use this approach with the Strings. Because, Strings are immutable. Hence, every time you concat a String a separate String object is created. Consider using StringBuilder instead.

Читайте также:  Found problems related to java

Using Java 8 String.join

Since Java 8, the String has new method – called as join.

List words = Arrays.asList("Convert", "List", "of", "Strings", "To", "String"); String output = String.join(",", words); System.out.println(output); // Output: // Convert,List,of,Strings,To,StringCode language: Java (java)

Moreover, this this approach also works with Set or any other collection that implements Iterable.

Set set = Stream.of("Convert", "List", "of", "Strings", "To", "String").collect(Collectors.toSet()); String output = String.join(" ", set); System.out.println(output); // Output: // Convert of List To String StringsCode language: Java (java)

However, don’t forget that Set is an Unordered collection. Hence, you may see the sequence of words in output varies.

Using Java Streams to Concatenate String

Java Streams also provide a convenient way of Joining Streams. The streams api provides a special collector called as Collectors.joining specifically for joining Strings.

String output = Stream.of("Convert", "List", "of", "Strings", "To", "String") .collect(Collectors.joining(",")); System.out.println(output); // Output: // Convert,List,of,Strings,To,StringCode language: Java (java)

Moreover, you can also add a prefix and suffix to the concatenated string.

String output = Stream.of("Convert", "List", "of", "Strings", "To", "String") .collect(Collectors.joining(",", "[", "]")); System.out.println(output); // Output: // [Convert,List,of,Strings,To,String]Code language: Java (java)

Summary

In this short tutorial, we have seen different techniques of Joining a String from List of Strings in Java. We have seen a manual way of concatenating string with and without a delimiter. Also we saw the join method from the String class. Finally, we saw Java streams Collectors.joining method to join string using a delimiter along with a prefix and a suffix.

Источник

Java 8 — Converting a List to String with Examples

Twitter Facebook Google Pinterest

A quick guide to convert List to String in java using different methods and apache commons api with examples.

1. Overview

Next, Collection to String with comma separator or custom delimiter using Java 8 Streams Collectors api and String.join() method.

For all the examples, input list must be a type of String as List otherwise we need to convert the non string to String. Example, List is type of Double then need to convert then double to string first.

Java 8 Streams- Converting a List to String with Examples.png

2. List to String Using Standard toString() method

List.toString() is the simplest one but it adds the square brackets at the start and end with each string is separated with comma separator.

The drawback is that we can not replace the comma with another separator and can not remove the square brackets.

package com.javaprogramto.convert.list2string; import java.util.Arrays; import java.util.List; /** * Example to convert List to string using toString() method. * * @author javaprogramto.com * */ public class ListToStringUsingToStringExample < public static void main(String[] args) < // creating a list with strings. Listlist = Arrays.asList("One", "Two", "Three", "Four", "Five"); // converting List to String using toString() method String stringFromList = list.toString(); // priting the string System.out.println("String : "+stringFromList); > >
String : [One, Two, Three, Four, Five]

3. List to String Using Java 8 String.join() Method

The above program works before java 8 and after. But, java 8 String is added with a special method String.join() to convert the collection to a string with a given delimiter.

import java.util.Arrays; import java.util.List; /** * Example to convert List to string using String.join() method. * * @author javaprogramto.com * */ public class ListToStringUsingString_JoinExample < public static void main(String[] args) < // creating a list with strings. Listlist = Arrays.asList("One", "Two", "Three", "Four", "Five"); // converting List to String using toString() method String stringFromList = String.join("~", list); // priting the string System.out.println("String with tilde delimiter: "+stringFromList); // delimiting with pipe | symbol. String stringPipe = String.join("|", list); // printing System.out.println("String with pipe delimiter : "+stringPipe); > >
String with tilde delimiter: One~Two~Three~Four~Five String with pipe delimiter : One|Two|Three|Four|Five

4. List to String Using Java 8 Collectors.joining() Method

Collectors.join() method is from java 8 stream api. Collctors.joining() method takes delimiter, prefix and suffix as arguments. This method converts list to string with the given delimiter, prefix and suffix.

Look at the below examples on joining() method with different delimiters. But, String.join() method does not provide the prefix and suffix options.

If you need a custom delimiter, prefix and suffix then go with these. If you do not want the prefix and suffix then provide empty string to not to add any before and after the result string.

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Example to convert List to string using Collectors.joining() method. * * @author javaprogramto.com * */ public class ListToStringUsingString_JoinExample < public static void main(String[] args) < // creating a list with strings. Listlist = Arrays.asList("One", "Two", "Three", "Four", "Five"); // using java 8 Collectors.joining with delimiter, prefix and suffix String joiningString = list.stream().collect(Collectors.joining("-", "")); // printing System.out.println("Collectors.joining string : "+joiningString); String joiningString3 = list.stream().collect(Collectors.joining("@", "", "")); // printing System.out.println("Collectors.joining string with @ separator : "+joiningString3); > >
Collectors.joining string : Collectors.joining string with @ separator : One@Two@Three@Four@Five

5. List to String Using Apache Commons StringUtils.join() method

Finally way is using external library from apache commons package. This library has a method StringUtils.join() which takes the list and delimiter similar to the String.join() method.

import org.apache.commons.lang3.StringUtils; /** * Example to convert List to string using apache commons stringutils.join() method. * * @author javaprogramto.com * */ public class ListToStringUsingStringUtils_JoinExample < public static void main(String[] args) < // creating a list with strings. Listlist = Arrays.asList("One", "Two", "Three", "Four", "Five"); // using java 8 Collectors.joining with delimiter, prefix and suffix String joiningString = StringUtils.join(list, "^"); // printing System.out.println("StringUtils.join string with ^ delimiter : "+joiningString); String joiningString3 = StringUtils.join(list, "$"); // printing System.out.println("StringUtils.join string with @ separator : "+joiningString3); > >
StringUtils.join string with ^ delimiter : One^Two^Three^Four^Five StringUtils.join string with @ separator : One$Two$Three$Four$Five

6. Conclusion

In this article, we’ve seen how to convert List to String in java using different methods before and after java 8.

or If you want to add a prefix or suffix then use stream api Collectors.joining() method with delimiter, prefix and suffix values.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

A quick guide to convert List to String in java using different methods and apache commons api with examples.

Источник

Java List to String

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List.We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

Using + operator

This is not an efficient way so, normally avoid it.We use concate( + ) operator to add one by one element from array inside loop and assign it into String.

Using String’s join method in java 8

String’s join method is introduced in Java 8 . This method is very handy to create delimited separated String from list.

This approach will work only for List of String. In case, if you have list of Double, then you can use java 8‘s Collectors to join the String.
Here is an example:

As you can see, we have used Collectors.joining(«,») to join elements of String by ,

Using Apache common lang3

You can also use Apache common’s StringUtils to convert list to String.
Here is the dependency which you need to add for Apache common lang3 in pom.xml .

Using Guava library

You can also use Guava’s Joiner class to convert list to String.
Here is the dependency which you need to add for guava in pom.xml .

As you can see, we have used com.google.common.base.Joiner class to join elements of String by *

Sometimes, we just need to print elements of the list. We can simply use toString() method
Let’s understand with the help of example.

Did you notice we did not even call toString() method on intList object?
JVM internally calls toString() method of type of element within this list. In this case, we have list of Integers, so it will call Integer’s toString() method.

In case, you have custom object, then you should override toString() method, else it will give you unexpected results.
Let’s see with the help of example
Create a simple class named Color.java

Источник

Оцените статью