Convert comma separated String to List

List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.


Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.

Answer from AlexR on Stack Overflow
Discussions

java - Split List<String[]> into List<List<String[]>> - Code Review Stack Exchange
We have a list of string arrays i.e. List (which we got from a csv) which follows the hierarchy: 0000 3000 5000 5000 5000 . . . 3900 3000 5000 5000 ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
October 28, 2021
java - How to convert a String into an ArrayList? - Stack Overflow
In my String, I can have an arbitrary number of words which are comma separated. I wanted each word added into an ArrayList. E.g.: String s = "a,b,c,d,e,........."; More on stackoverflow.com
🌐 stackoverflow.com
java - convert comma separated string to list without intermediate container - Stack Overflow
I need to convert comma separated string to list of integers. For example if I have following string String numbersArray = "1, 2, 3, 5, 7, 9,"; Is there a way how to convert it at once to List More on stackoverflow.com
🌐 stackoverflow.com
Java 8 convert String of ints to List<Integer> - Stack Overflow
I have a String: String ints = "1, 2, 3"; I would like to convert it to a list of ints: List intList I am able to convert it to a list of strings this way: List list = More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
🌐
Baeldung
baeldung.com › home › java › java string › convert a comma separated string to a list in java
Convert a Comma Separated String to a List in Java
September 3, 2025 - In our first solution, we’ll convert a string to a list of strings and integers using core Java. First, we’ll split our string into an array of strings using split, a String class utility method.
🌐
Benchresources
benchresources.net › home › java › java 8 – how to split a string and collect to any collection ?
Java 8 - How to split a String and Collect to any Collection ? - BenchResources.Net
September 28, 2022 - Finally, iterate & print List to console using List.forEach() method ... package in.bench.resources.split.string; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class SplitStringAndCollectToListUsingJava8Stream { public static void main(String[] args) { // original string String fruits = "Grapes, Apple, Mango, Banana, Orange, Melons"; System.out.println("Original comma-separted String :- \n" + fruits); // split String based on comma List<String> fruitList = Arrays.stream(fruits.split("\\,")) // split on comma .map(str -> str.trim()) // remove white-spaces .collect(Collectors.toList()); // collect to List // print to console System.out.println("\nIterating & printing split-ted String from List :- "); fruitList.forEach(System.out::println); } }
🌐
Programming.Guide
programming.guide › java › split-string-into-arraylist.html
Java: How to split a String into an ArrayList | Programming.Guide
In Java, difference between default, public, protected, and private ... Executing code in comments?! ... input = "aaa,bbb,ccc"; // To array String[] arr = input.split(","); // To fixed-size list List<String> l = Arrays.asList(input.split(",")); // To ArrayList List<String> l2 = new ...
🌐
Mkyong
mkyong.com › home › java › java – convert comma-separated string to a list
Java - Convert comma-separated String to a List - Mkyong.com
April 14, 2017 - package com.mkyong.utils; import java.util.Arrays; import java.util.List; public class TestApp1 { public static void main(String[] args) { String alpha = "A, B, C, D"; //Remove whitespace and split by comma List<String> result = Arrays.asList(alpha.split("\\s*,\\s*")); System.out.println(result); } } Output · [A, B, C, D] No need to loop the List, uses the new Java 8 String.join ·
🌐
Initial Commit
initialcommit.com › blog › java-convert-comma-separated-string-to-list
Java – Convert comma-separated String to List - Initial Commit
public static List<String> convertUsingJava8(String commaSeparatedStr) { String[] commaSeparatedArr = commaSeparatedStr.split("\\s*,\\s*"); List<String> result = Arrays.stream(commaSeparatedArr).collect(Collectors.toList()); return result; } This tutorial shows several ways for converting a comma-separated String to a List in Java.
🌐
How to do in Java
howtodoinjava.com › home › string › split csv string using regex in java
Split CSV String using Regex in Java
February 22, 2023 - String[] tokenArray = blogName.split("\\s*,\\s*"); List<String> tokenList = Arrays.asList(tokenArray); To get the mutable ArrayList, copy all elements from the read-only list received from the above example into a new ArrayList object.
Find elsewhere
Top answer
1 of 3
6

Motivations for improvement

I think "solving in 1 or 2 statements" is not a good target. Aiming for Java 8 features for the sake of using Java 8 features is also not a good target. A better target would be a combination of:

  • correct and reasonably robust
  • easy to understand
  • reasonably efficient

Here's a bit shorter and more efficient, but pretty bad solution:

private List<List<String[]>> splitIntoBlocks(List<String[]> rows) {
    List<List<String[]>> blocks = new ArrayList<>();

    int start = 0;
    for (int index = 0; index < rows.size(); index++) {
        String marker = rows.get(index)[0];
        if (marker.equals("3000")) {
            start = index;
        } else if (marker.equals("3900")) {
            int end = index + 1;
            blocks.add(rows.subList(start, end));
        }
    }

    return blocks;
}

This is bad (as bad as the original code), because it doesn't validate the input. It will only work correctly with input in the assumed format, which it doesn't verify, and it doesn't detect or signal when something is wrong, which could lead to nasty bugs.

Validating inputs

The posted code assumes the input follows a certain format. It should at least document the assumptions, and state if the caller can be trusted to enforce those assumptions.

As you mentioned, the input comes from CSV files. Since the expected format is not captured by the List<String[]> type, I would be very cautious. A verification is needed somewhere to avoid bugs or undefined behavior, for example the following checks come to mind:

  • There are the same number of START and END markers (you already did this one)
  • The START and END markers don't overlap
  • (optional?) There are no garbage records after an END and before the next START
  • The rows are not empty (avoid crashing due to index out of bounds exceptions)

When any of these assumptions fail, I would either raise a custom exception that the caller can handle, or else throw IllegalArgumentException to fail fast.

So in fact, instead of making the posted code shorter, I'm suggesting to actually make it longer, by adding more validation logic.

Making the code easier to understand

Another answer already mentioned to improve the variable names. (I suggest following Java conventions with camelCase names, so startIndices and endIndices.)

The values "3000" and "3900" are magic strings. It would be better to use private static final constants for such values, so that they stand out, and with a descriptive name.

Building the lists of startIndices and endIndices use the same logic, duplicated. It would be good to extract to a helper method.

When returning a container type, it's usually more practical to return an empty container instead of null.

2 of 3
4

Low hanging fruit

l1 and l2 are very opaque variable names. start_indices and end_indices would be much more descriptive.


        //get all position of 3000
        List<Integer> l1 = IntStream.range(0,rows.size())
                .filter(i->rows.get(i)[0].equals("3000"))
                .boxed()
                .collect(Collectors.toList());

This code takes int indices, boxes them into Integer indices, and collects them into a List<Integer>. This results in many small objects in memory.

We can avoid the boxing, by replacing .boxed().collect(Collectors.toList()) with .toArray() and changing the variable type to int[].

        // get positions of all "3000"'s
        int[] start_indices = IntStream.range(0,rows.size())
                .filter(i->rows.get(i)[0].equals("3000"))
                .toArray();

Apply similar change to the group end indices, and corresponding changes to the final res construction.

Single Pass

The above is still passing over the rows input 3 times; the first to collect the starting indices, the second to collect the ending indices, and the third time to assemble the result. Three passes means you cannot apply this grouping operation on an ephemeral stream; it requires a concrete collection that can be repeatedly iterated over.

Moreover, an IntStream is being used to generate indices into the rows list -- a hack -- which requires an ArrayList or similar \$O(1)\$-indexable collection to avoid quadratic time complexity.

It would be much better to perform a single pass over the stream of data, and collecting the required groups along the way:

private List<List<String[]>> splitIntoBlocks(List<String[]> rows) {
   return rows.stream().collect(Block.collector());
}

Well, the above clearly solves the "looking for someone to solve this in perhaps 1 or 2 statements" request, but clearly additional work is still required. The Block.collector() class is required, writing of which (to handle possible splitting & parallel stream handling) is a non-trivial exercise. See Collector.of(...)

🌐
Mkyong
mkyong.com › home › java › how to split a string in java
How to split a string in Java - Mkyong.com
February 9, 2022 - package com.mkyong.string.split; ... System.out.println(output); } } ... We can use \\s+ (which means one or more whitespace characters in regex) to split a string by spaces....
🌐
BeginnersBook
beginnersbook.com › 2015 › 05 › java-string-to-arraylist-conversion
Java – How to Convert a String to ArrayList
September 20, 2022 - We are splitting the string based on comma (,) as delimiter to get substrings. These substrings are assigned to ArrayList as elements. import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class JavaExample { public static void main(String args[]){ String num = "22,33,44,55,66,77"; String str[] = num.split(","); List<String> al = new ArrayList<String>(); al = Arrays.asList(str); for(String s: al){ System.out.println(s); } } }
🌐
Java67
java67.com › 2017 › 09 › how-to-convert-comma-separated-string-to-ArrayList-in-java-example.html
How to Convert a Comma Separated String to an ArrayList in Java - Example Tutorial | Java67
Well, Java doesn't provide any such constructor or factory method to create ArrayList from delimited String, but you can use String.split() method and Arrays.asList() method together to create an ArrayList from any delimited String, not just ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-a-string-to-arraylist-in-java
How to Convert a String to ArrayList in Java? - GeeksforGeeks
July 23, 2025 - Splitting the string by using the Java split() method and storing the substrings into an array.
🌐
Baeldung
baeldung.com › home › java › java streams › string operations with java streams
String Operations with Java and Stream API | Baeldung
January 8, 2024 - public static Map<String, String> arrayToMap(String[] arrayOfString) { return Arrays.asList(arrayOfString) .stream() .map(str -> str.split(":")) .collect(toMap(str -> str[0], str -> str[1])); } Here, “:” is the key-value separator for all the elements in String array. Please remember that in order to avoid compilation error, we need to ensure that code is compiled using Java 1.8.
🌐
Attacomsian
attacomsian.com › blog › java-string-with-separator-to-list
Convert a comma-separated string to a list in Java
October 29, 2022 - The String class in Java provides split() method to split a string into an array of strings.