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
🌐
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 this example, we used the splitPreserveAllTokens method to split our countries string, whereas we used the split method to split our ranks string. Even though both these functions split the string into an array, the splitPreserveAllTokens preserves all tokens including the empty strings created by adjoining separators, while the split method ignores the empty strings.
Discussions

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
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
regex - convert a string to a list of object using Java 8 - Stack Overflow
I have a string "Red apple, blue banana, orange". How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few pos... More on stackoverflow.com
🌐 stackoverflow.com
arraylist - split string and store it into HashMap java 8 - Stack Overflow
I want to split below string and store it into HashMap. String responseString = "name~peter-add~mumbai-md~v-refNo~"; first I split the string using delimeter hyphen (-) and storing it into ArrayL... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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); } }
🌐
Coderanch
coderanch.com › t › 684973 › java › Split-string-list-string-regex
Split the string and get a list of string using regex (Features new in Java 8 forum at Coderanch)
I am able to do it in earlier Java version but trying things using Java 8 features. Hope you understand. Thanks, Atul ... In one case you are iterating the String in a loop and adding all the group()s to a List: easy enough with Java5‑style code. With the input you showed, you are going to run the loop thrice and get a three‑element List.
🌐
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.
🌐
Programming.Guide
programming.guide › java › split-string-into-arraylist.html
Java: How to split a String into an ArrayList | Programming.Guide
Generating a random point within a circle (uniformly) Here are a few ways to split (or convert, or parse) a string of comma separated values: input = "aaa,bbb,ccc"; // To array String[] arr = input.split(","); // To fixed-size list List<String> l = Arrays.asList(input.split(",")); // To ArrayList ...
🌐
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 ·
🌐
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; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StringSplitJava8 { public static void main(String[] args) { String phone = "012-3456789"; List<String> output = Arrays.stream(phone.split("-")) .collect(Collectors.toList()); System.out.println(output); } }
Find elsewhere
🌐
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. ArrayList<String> tokenArrayList = new ArrayList(Arrays.asList(tokenArray)); If we want to convert a List to CSV, then we can use String.join() method provided by Java 8.
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(...)

🌐
javathinking
javathinking.com › blog › convert-sting-to-list-in-java
Converting String to List in Java — javathinking.com
The Java 8 Stream API provides a functional and concise way to convert a String to a List. You can use the Pattern.splitAsStream() method to split the String into a stream of tokens and then collect them into a List.
🌐
javathinking
javathinking.com › blog › convert-a-string-to-list-in-java
Converting a String to a List in Java — javathinking.com
Q: Which method is the most efficient for converting a string to a list? A: For simple cases, using String.split() and Arrays.asList() is usually sufficient and quite efficient. The Java 8 Stream API provides more flexibility and readability, especially when you need to perform additional operations on the elements.
🌐
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 ...
🌐
Baeldung
baeldung.com › home › java › java streams › string operations with java streams
String Operations with Java and Stream API | Baeldung
January 8, 2024 - Learn how to split a comma-separated String into a list of Strings and how to join a String array into a comma-separated String.
🌐
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); } } } Output: 22 33 44 55 66 77 ·