Interested in converting a List to a String in Java? Explore the process of transforming a Java Collections List of elements into a String in Java. In this article, we delve into the top 12 methods for this conversion, providing a platform for you to learn and implement them effortlessly.

To Convert a list to string in java, You can do by,

  • 1. Using toString()
  • 2. List Of Object To String
  • 3. Join Method(StringUtils)
  • 4. Stream Collectors
  • 5. Comma Separator(delimiter)
  • 6. Convert Character List To String
  • 7. With Double Quotes
  • 8. Sort Method
  • 9. toJSON Method
  • 10. The method in Java 8
  • 11. ReplaceAll Method
  • 12. LinkList to String

Introduction

Basically List in Java is an ordered collection or a default sequence.

List accepts duplicate elements unlike Map doesn’t accept duplicate values and also holds the object in key-value pairs.

We can print the contents of a List element in a readable form while debugging the code, which is helpful.

List interface and String class were part of Java object-oriented programming API.

We can add any type of Java object to a List. If the List does not type, then using Java Generics we can apply objects of various types in the same List.

Typically we will enclose the generic type in square brackets.

Using toString()

From the below Java program, let’s see how to convert convert Java list to string array using the toString method.

We are passing an integer argument(number) to create a java string array using the Java Arrays asList() method.

In other words, we are passing a list of integers as an array to list.

public static void main(String[] args) {
try {
	List<Integer> list = Arrays.asList(0, 1, 2, 3);
	System.out.println(list);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
    
Output:
[0, 1, 2, 3]

As per the output code above, we can see a list of array values printed as an array of strings or string array in java.

This way of implementation uses the inbuilt toString() method within the List.

Here Integer Java generics type has an internal implementation of the toString() method.

In the above example, we used Arrays.asList to create an array in java in an optimal manner.

But we can also use standard ArrayList in java and can add the values using the list.add() method or addAll method.

Also, we can convert from traditional ArrayList to String Array using ArrayList Class.

Interview Question 1 -> Primitive Types in Java:

boolean, byte, char, short, int, long, float, and double are the primitive types in Java API.

You May Like,

Java List to Comma Separated String:

Utilize the String.join() method or a custom delimiter with stream and Collectors.joining()


List list = Arrays.asList("apple", "banana", "cherry");
String result = String.join(", ", list);
// or
String result = list.stream().collect(Collectors.joining(", "));

Java Comma Separated String to List:

Use the String.split() method along with Arrays.asList() to convert a comma-separated string to a list.


String str = "apple, banana, cherry";
List list = Arrays.asList(str.split(", "));

List of Object to String

Let’s see how Object toString() method works as per below java program class.

public class HelloObject {
	
	String name;
	int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "HelloObject [name=" + name + ", age=" + age + "]";
	}
	
}

Here the custom toString() function which returns in a custom string object format.

public static void main(String[] args) {
try {
    	List<HelloObject> list = new ArrayList<HelloObject>();
		HelloObject hb = new HelloObject();
		hb.setName("James");
		hb.setAge(25);
		list.add(hb);
		System.out.println(List);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
	
Output:
[HelloObject [name=James, age=25]]

Here custom toString() in the HelloObject will convert the Object into String representation format.

As per output, we can see the list of string.

Interview Question 2 -> ArrayList vs LinkedList:

Array List in java API applies a dynamic array to store the elements.

Whereas LinkedList uses a double linked list to store the elements.

Also, the ArrayList String value can convert to a byte array using the Java programming language.

Again both ArrayList and LinkedList accept duplicate values.

But we can remove duplicates using plain Java code, Lambdas, Guava.

java list string Java String to List:

You can convert a Java String to a List by using the Arrays.asList() method after splitting the string.


String str = "apple, banana, cherry";
List list = Arrays.asList(str.split(", "));

Join Method (StringUtils)

We can use the join method of Apache Commons Lang StringUtils class to achieve the java list to string conversion.

public static void main(String[] args) {
try {
	List<Integer>list = Arrays.asList(0, 1, 2, 3);
	System.out.println(StringUtils.join(list, " "));
	} catch (Exception e) {
		e.printStackTrace();
	}
}
    
Output:
0 1 2 3

StringUtils.join method have inbuilt toString() method.

As we can see from the above output, it prints the List elements as String data type with space delimiter.

we can also use java regular expressions to define a search pattern for strings.

A regular expression is best applicable for pattern matching of expressions or functions.

Here is the maven dependency for Apache commons-lang StringUtils class of java API.

you can use this in your project pom.xml file as a dependency.


<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

The latest version of the dependency will be available here.

Stream Collectors

convert list to string in java

java list to string

Now let’s use the Java Util Stream Collectors API package to convert List to String.

Here we leverage Java streams method stream() for conversion.

public static void main(String[] args) {
try {
	List<Integer> list = Arrays.asList(1, 2, 3);
	String result = list.stream().
		map(i -> String.valueOf(i)).
		collect(Collectors.joining("/", "(", ")"));
	System.out.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
        
Output:		
(1/2/3)

In the above example, we can see the usage of the stream(). map, note that it is different from standard java map.

The Collectors.joining() method can be used along with the stream() method to convert a list to a string seamlessly.


import java.util.*;
import java.util.stream.*;

public class ListToString {
    public static void main(String[] args) {
        List fruits = Arrays.asList("Apple", "Banana", "Cherry");
        String result = fruits.stream()
                              .collect(Collectors.joining(", "));
        System.out.println(result);  // Output: Apple, Banana, Cherry
    }
}

Comma Separator(delimiter)

Let’s go through how to convert using comma-separated values.

public static void main(String[] args) {
	try {
		List<String> countries = Arrays.asList("USA", "UK", "Australia", "India");
		String countriesComma = String.join(",", countries);
		System.out.println(countriesComma);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
Output:
USA,UK,Australia,India

As per the output above, we can see conversion using delimiter i,e. separated by Comma or Comma separated.

Using join method, you can convert List to String with Separator comma, backslash, space, and so on.

list to string in java

Convert Character List to String

Let’s go through how to convert List of Characters to String using StringBuilder class.

The StringBuilder class in Java is a mutable sequence of characters, providing an efficient means of handling and manipulating strings. Especially when dealing with conversions from lists to strings, StringBuilder comes as a highly recommended option. This article delves deeper into the usage of StringBuilder for such conversions, demonstrating its efficacy particularly when the list contains types other than String.

Converting a List to a String

One common scenario in Java programming involves converting a list of elements into a string. The StringBuilder class significantly optimizes this task by reducing the time complexity compared to traditional string concatenation. Below, we walk through the process of utilizing StringBuilder to achieve this conversion, illustrated with different types of lists – List<Integer>, List<Character>, and List<String>.

With List of Integers


import java.util.Arrays;
import java.util.List;

public class ListToString {
    public static void main(String[] args) {
        List integerList = Arrays.asList(1, 2, 3, 4, 5);
        StringBuilder stringBuilder = new StringBuilder();
        
        for(Integer number : integerList) {
            stringBuilder.append(number);
            stringBuilder.append(", ");
        }
        
        stringBuilder.setLength(stringBuilder.length() - 2);  // Removing the trailing comma and space
        String result = stringBuilder.toString();
        System.out.println(result);  // Output: 1, 2, 3, 4, 5
    }
}

With List of Characters


import java.util.Arrays;
import java.util.List;

public class ListToString {
    public static void main(String[] args) {
        List charList = Arrays.asList('a', 'b', 'c', 'd', 'e');
        StringBuilder stringBuilder = new StringBuilder();
        
        for(Character ch : charList) {
            stringBuilder.append(ch);
        }
        
        String result = stringBuilder.toString();
        System.out.println(result);  // Output: abcde
    }
}


One more example with list of characters.

public static void main(String[] args) {
	try {
        List<Character> list =  
                Arrays.asList('c', 's', 'v'); 
        StringBuilder sb = new StringBuilder(); 
        for (Character chr : list) { 
            sb.append(chr); 
        } 
        // convert to string 
        String result = sb.toString(); 
        System.out.println(result); 
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Output:
csv

With List of Strings


import java.util.Arrays;
import java.util.List;

public class ListToString {
    public static void main(String[] args) {
        List stringList = Arrays.asList("apple", "banana", "cherry");
        StringBuilder stringBuilder = new StringBuilder();
        
        for(String fruit : stringList) {
            stringBuilder.append(fruit);
            stringBuilder.append(" ");
        }
        
        stringBuilder.setLength(stringBuilder.length() - 1);  // Removing the trailing space
        String result = stringBuilder.toString();
        System.out.println(result);  // Output: apple banana cherry
    }
}

with Double Quotes

Using Apache Commons StringUtils package, convert List to String with Quotes using Java.

Refer to the below implementation
public static void main(String[] args) {
	try {
	 List<String> countries = Arrays.asList("USA", "UK", "Australia", "India");
	 String join = StringUtils.join(countries, "\", \"");
	 String wrapQuotes = StringUtils.wrap(join, "\"");	 
	 System.out.println(wrapQuotes);
	 } catch (Exception e) {
	  e.printStackTrace();
	 }
}
Output:
"USA", "UK", "Australia", "India"

Of course, you can convert using Single Quotes with Single String as well.

Sort Method

we can convert using Java Sort with the below implementation.

public static void main(String[] args) {
	try {
	 List<String> countries = Arrays.asList("USA", "UK", "Australia", "India");
	 countries.sort(Comparator.comparing(String::toString)); 
	 System.out.println(countries);
	 } catch (Exception e) {
		e.printStackTrace();
	 }
}
Output:
[Australia, India, UK, USA]

toJson Method

Let’s convert List to String JSON in Java using Google GSON library.

It is a straight forward method ToJson() which will set and convert the input to JSON String.

public static void main(String[] args) {
	try {
	 List<String> countries = Arrays.asList("USA", "UK", "Australia", "India");
	 String json = new Gson().toJson(countries);
	 System.out.println(json);
	 } catch (Exception e) {
	   e.printStackTrace();
	 }
}

Output:
["USA","UK","Australia","India"]

In Java 8

Let’s convert List to String using String.join() method in Java 8.

public static void main(String[] args) {

	try {
		List<String> list = Arrays.asList("USA", "UK", "INDIA");
		String delimiter = "-";
		String result = String.join(delimiter, list);
		System.out.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Output:
USA-UK-INDIA
Performance Comparison

When dealing with large lists, the performance of the conversion method becomes crucial. Java 8’s Stream API not only simplifies the syntax but also provides efficient processing, especially when combined with StringBuilder under the hood.


import java.util.*;
import java.util.stream.*;

public class PerformanceComparison {
    public static void main(String[] args) {
        List numbers = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            numbers.add(i);
        }

        long start = System.currentTimeMillis();
        String result = numbers.stream()
                              .map(String::valueOf)
                              .collect(Collectors.joining(", "));
        long end = System.currentTimeMillis();
        System.out.println("Stream and Collectors: " + (end - start) + " ms");

        start = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        for (Integer number : numbers) {
            sb.append(number).append(", ");
        }
        result = sb.toString();
        end = System.currentTimeMillis();
        System.out.println("StringBuilder: " + (end - start) + " ms");
    }
}

replaceAll Method

Lets convert List to String using replaceAll() and String.join() method.

You can also notice inline lambda expressions used in the replaceAll method.

public static void main(String[] args) {

	try {
		List<String> countries = Arrays.asList("usa", "uk", "india");
		countries.replaceAll(r -> r.toUpperCase());
		String result = String.join(" ", countries);
		System.out.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
	}

Output:
USA UK INDIA

Let's convert LinkedList to String using String.join() method.

public static void main(String[] args) {

		try {
			LinkedList<String> list = new LinkedList();
			list.add("USA");
			list.add("UK");
			list.add("INDIA");
		    String result = String.join(" ", list);
		    System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
Output:
USA UK INDIA

In case of any issues during conversion, we can notice the error message in the console log.

To conclude, in this tutorial we gone through different ways to convert a Java List to String data type.

List to String methods conversion is also common in other programming languages like JavaScript, Python, Jquery.

In a nutshell, JavaScript uses an str function for concatenate, likewise, the python program uses join method for conversion and concatenate a string.

Interested to read JavaScript resources, check out this JavaScript split method article.

Frequently Asked Questions (FAQs)

How can I convert a List to a String in Java?

In Java, there are several methods to convert a List to a String. Some common methods include using the toString() method, the String.join method, or utilizing Stream Collectors.

How can I convert a List of Integers to a String in Java?

You can use the List.toString() method to convert a List of Integers to a String. Alternatively, you could loop through the list and convert each integer to a string individually.

How can I remove brackets when converting a List to a String in Java?

The List.toString() method will include brackets. To remove them, you can use the substring method on the resulting string to remove the first and last characters, or utilize other methods like String.join or Collectors.joining.

What is the Java 8 way of converting a List to a String?

In Java 8, you can use the String.join method or Stream Collectors with the joining collector to convert a List to a String.

How can I convert a List of Characters to a String in Java?

You can use the List.toString() method and then replace the brackets and commas, or utilize the StringBuilder or StringJoiner classes to concatenate the characters into a string.

How can I use streams to convert a List to a String in Java?

You can use the Collectors.joining method along with the stream() method of the List to convert it to a String.

Can I use the toString() method to convert any List to a String in Java?

Yes, you can use the toString() method on a List in Java to convert it to a String. However, the format of the resulting string may not always be desirable, especially if the List contains complex objects or primitives other than String.

How can I convert a List to a comma-separated String in Java?

You can use the String.join method, passing a comma as the separator, or utilize Stream Collectors with Collectors.joining passing a comma as the delimiter.

What are some common issues faced when converting a List to a String in Java?

Common issues include undesired formatting due to the default behavior of the toString() method, or type mismatch issues when the List contains non-String elements.

Are there libraries or utilities in Java that can help with converting a List to a String?

Yes, libraries such as Apache Commons Lang provide utility methods like StringUtils.join which can be used to convert a List to a String in Java.

Keeping sharing java tutorials and happy coding 🙂
4.9/5 - (37 votes)

Pin It on Pinterest

Share This