Is there a simple way to parse the following String to List of Integers:
String s = \"1,2,5-9,11,12\"
// expected values list: [1,2,5,6,7,8,9,11,12]
List
This should work:
public class StringMagic
{
public static void main(String[] args)
{
String s = "1,2,5-9,11,12";
// expected values list: [1,2,5,6,7,8,9,11,12]
List values = magicallyGetListFromString(s);
for (Integer integer : values)
{
System.out.println(integer);
}
}
public static List magicallyGetListFromString(String s)
{
List numberList = new ArrayList();
String[] numbers = s.split(",");
for (String string : numbers)
{
if (!string.contains("-"))
{
numberList.add(Integer.parseInt(string));
}
else
{
String[] limits = string.split("-");
int bottomLimit = Integer.parseInt(limits[0]);
int upperLimit = Integer.parseInt(limits[1]);
for(int i = bottomLimit; i <= upperLimit; i++)
{
numberList.add(i);
}
}
}
return numberList;
}
}