How to convert List to String using Java 8

In this post we will see How to Convert List to String using Java 8 along with few examples. Actually We are going convert List to Comma separated String means each value should be separated by comma or any delimiter of our choice.

Java 8 : How to Convert List to String
List of String can be converted into String by two  ways. In Both the ways we should specify the delimiter, which will join each values.

  1. Using String,join() method.
  2. Using Collectors.joining

1. Convert List to String using String join method


public class Java8Collect {
	public static void main(String[] args) {
		List<String> listOfStrings = Arrays.asList("apple", "apple", "banana", "apple", "coconut", "banana");
		String value1 =  listToStringUsingJoin(listOfStrings);
		System.out.println(value1);
	}

	
	private static String listToStringUsingJoin(List<String> listOfStrings) {
		return String.join(",", listOfStrings);	
	}
	
}

2. Convert List to String using Collectors.joining


public class Java8Collect {
	public static void main(String[] args) {
		List<String> listOfStrings = Arrays.asList("apple", "apple", "banana", "apple", "coconut", "banana");
		String value2 = listToStringUsingCollectors(listOfStrings);
		System.out.println(value2);
	}
	
	private static String listToStringUsingCollectors(List<String> listOfStrings) {
		return listOfStrings.stream().collect(Collectors.joining(":"));
	}
}


The output of two methods

apple,apple,banana,apple,coconut,banana
apple:apple:banana:apple:coconut:banana

Add a Comment

Your email address will not be published. Required fields are marked *