Java List from Array asList(String str)

Here you can find the source of asList(String str)

Description

take a string of ints (eg: 1,2,3,4), and return a List of Integers

License

Open Source License

Declaration

static public List<Integer> asList(String str) 

Method Source Code


//package com.java2s;
/* This program is free software: you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public License
 as published by the Free Software Foundation, either version 3 of
 the License, or (at your option) any later version.
    // ww  w .  ja v  a  2  s  .c om
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
    
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>. */

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

public class Main {
    /** take a string of ints (eg: 1,2,3,4), and return a List of Integers */
    static public List<Integer> asList(String str) {
        return asList(str, ",");
    }

    /** take a string of ints (eg: 1[sep]2[sep]3[sep]4), and return a List of Integers */
    static public List<Integer> asList(String str, String sep) {
        List<Integer> retVal = new ArrayList<Integer>();
        try {
            String[] s = str.split(sep);
            for (int i = 0; i < s.length; i++) {
                Integer k = null;
                try {
                    k = Integer.parseInt(s[i].trim());
                } catch (Exception m) {
                }
                if (k != null)
                    retVal.add(k);
            }
        } catch (Exception e) {
        }

        return retVal;
    }
}

Related

  1. asList(Object value)
  2. asList(Object[] array)
  3. asList(Object[] array)
  4. asList(Set set)
  5. asList(String data)
  6. asList(String string)
  7. asList(String strList, String regex)
  8. asList(String val)
  9. asList(String valuesSeparatedBy, String delimiter)