Home » How to Split Strings in Java

How to Split Strings in Java

slices of pineapple on board

Here’s how to split Strings in Java.

import java.util.regex.Pattern;

public class SplittingStrings {

    private static final Pattern REGEX = Pattern.compile(", ");

    public static void main(String[] args) {
        System.out.println("Simple split: ");
        for (String column : simpleSplit()) {
            System.out.println(column);
        }

        System.out.println("Performant split: ");
        for (String column : performantSplit()) {
            System.out.println(column);
        }
    }

    private static String[] simpleSplit() {
        return "id, name, country, gender".split(", ");
    }

    // If you will split frequently, prefer this implementation.
    private static String[] performantSplit() {
        return REGEX.split("id, name, country, gender");
    }
}

If you have any questions, leave a comment or ask me on my social media.

Leave a Reply

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