Java 8 – How to convert String to ArrayList ?

In this article, we will discuss how to convert Comma-separated string values into List or specifically ArrayList

We will illustrate 2 examples for converting comma-separated String values into List,

  • CSV of Strings into List of String
  • CSV of Integers into List of String

1. CSV of Strings into ArrayList :

  • Below illustration converts string of comma-separated values into List of String

StringToArrayList1.java

package in.bench.resources.java.conversion;

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

public class StringToArrayList1 {

	public static void main(String[] args) {

		// 1. comma-separated string
		String str = "Mangoes,Apples,Grapes,Banana,Cherries";


		// 1.1 print to console
		System.out.println("CSV :- \n" + str);


		// 2. split and store in ArrayList
		ArrayList<String> arrayList = Arrays
				.stream(str.split(",")) // split
				.collect(Collectors.toCollection(ArrayList::new)); // store


		// 2.1 print to console
		System.out.println("\n\nArrayList of String elements :- \n");
		arrayList.forEach(System.out::println);
	}
}

Output :

CSV :- 
Mangoes,Apples,Grapes,Banana,Cherries


ArrayList of String elements :- 

Mangoes
Apples
Grapes
Banana
Cherries

2. CSV of Integers into ArrayList :

  • Below illustration converts string of comma-separated values into List of Integer as string contains integer values
  • To convert individual string into integer, use Integer.parseInt() method

StringToArrayList2.java

package in.bench.resources.java.conversion;

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

public class StringToArrayList2 {

	public static void main(String[] args) {

		// 1. comma-separated string
		String str = "1001,2002,3003,4004,5005";


		// 1.1 print to console
		System.out.println("CSV :- \n" + str);


		// 2. split and store in ArrayList
		ArrayList<Integer> arrayList = Arrays
				.stream(str.split(",")) // split
				.map(s -> Integer.parseInt(s)) // convert to String to Integer
				.collect(Collectors.toCollection(ArrayList::new)); // store


		// 2.1 print to console
		System.out.println("\n\nArrayList of Integer elements :- \n");
		arrayList.forEach(System.out::println);
	}
}

Output :

CSV :- 
1001,2002,3003,4004,5005


ArrayList of Integer elements :- 

1001
2002
3003
4004
5005

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java – How to add elements at the beginning and end of LinkedList ?