Turn a String with delimiters into a List. - Java java.lang

Java examples for java.lang:String Split

Description

Turn a String with delimiters into a List.

Demo Code


//package com.java2s;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] argv) {
        String string = "java2s.com";
        String delimiter = ".";
        System.out.println(toList(string, delimiter));
    }//from   w  ww .  j  a  va2  s.  c  om

    /**
     * Turn a String with delimiters into a List.
     * 
     * @param string
     *            The String to process
     * @param delimiter
     *            The String with delimiters with which to split the String by.
     */
    public static List toList(final String string, final String delimiter) {
        if (string == null || delimiter == null)
            return new ArrayList();

        StringTokenizer tokenizer = new StringTokenizer(string, delimiter);
        List result = new ArrayList(tokenizer.countTokens());

        while (tokenizer.hasMoreTokens())
            result.add(tokenizer.nextToken());

        return result;
    }
}

Related Tutorials