Java – Convert comma separated String to a List & Vice-versa

Java examples showing comma-separated String into a List and vice versa.

  • Comma-separated String to List
 

package com.pwn.collection;

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

public class CommaStringToList {

	public static void main(String[] args) {
		String city = "SFO,New York,Washington";

		/* Split string based on comma and convert to List using java.util.Arrays */
		List<String> cityList = Arrays.asList(city.split(","));

		System.out.println(cityList);
	}
}
[SFO, New York, Washington]

  • List to Comma-separated String
 

package com.pwn.collection;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ListToCommaString {

	public static void main(String[] args) {
		List<String> cityList = Arrays.asList("Washington",
				"New York", "SFO");

		/*
		 * Convert Arrays into String using java.util.stream.Collectors.joining method
		 */
		String city = cityList.stream()
				.collect(Collectors.joining(","));

		System.out.println(city);

	}

}
Washington,New York,SFO

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s