Creates a list of integers from a string within tokens. - Android java.util

Android examples for java.util:List

Description

Creates a list of integers from a string within tokens.

Demo Code


//package com.book2s;
import java.util.ArrayList;

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

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        String delimiter = "book2s.com";
        System.out.println(integerTokenToList(string, delimiter));
    }//from   ww w . j a  va 2s  .c  o  m

    /**
     * Creates a list of integers from a string within tokens. Empty tokens will
     * be omitted: If a string within tokens is <code>"1,,2,,3"</code> and the
     * delimiter string is <code>","</code>, the returned list of integers
     * contains the tree elements <code>1, 2, 3</code>.
     *
     * <em>It is expected, that each token can be parsed as an integer or is
     * empty!</em>
     *
     * @param string    String within tokens parsable as integer
     * @param delimiter Delimiter between the integer tokens. Every character
     *                  of the delimiter string is a separate delimiter. If
     *                  the string within tokens is <code>"1,2:3"</code>
     *                  and the delimiter string is <code>",:"</code>, the
     *                  returned list of integers contains the three elements
     *                  <code>1, 2, 3</code>.
     * @return          list of integers
     * @throws          NumberFormatException if the string contains a not empty
     *                  token that can't parsed as an integer
     */
    public static List<Integer> integerTokenToList(String string,
            String delimiter) {
        if (string == null) {
            throw new NullPointerException("string == null");
        }

        if (delimiter == null) {
            throw new NullPointerException("delimiter == null");
        }

        List<Integer> integerList = new ArrayList<>();
        StringTokenizer tokenizer = new StringTokenizer(string, delimiter);

        while (tokenizer.hasMoreTokens()) {
            integerList.add(Integer.parseInt(tokenizer.nextToken()));
        }

        return integerList;
    }
}

Related Tutorials