Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.
Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.
Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
Or, using Guava:
List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));
Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).
The ArrayList returned by Arrays.asList is not java.util.ArrayList. It's java.util.Arrays.ArrayList. So you can't cast it to java.util.ArrayList.
You need to pass the list to the constructor of java.util.ArrayList class:
List<String> items = new ArrayList<String>(Arrays.asList(CommaSeparated.split("\\s*,\\s*")));
or, you can simply assign the result:
List<String> items = Arrays.asList(CommaSeparated.split("\\s*,\\s*"));
but mind you, Arrays.asList returns a fixed size list. You cannot add or remove anything into it. If you want to add or remove something, you should use the 1st version.
P.S: You should use List as reference type instead of ArrayList.
You can't just cast objects around like they're candy. Arrays.asList() doesn't return an ArrayList, so you can't cast it (it returns an unmodifiable List).
However you can do new ArrayList(Arrays.asList(...));
Either write a simple method yourself, or use one of the various utilities out there.
Personally I use apache StringUtils (StringUtils.join)
edit: in Java 8, you don't need this at all anymore:
String joined = String.join(",", name);
Android developers are probably looking for TextUtils.join
Android docs: http://developer.android.com/reference/android/text/TextUtils.html
Code:
String[] name = {"amit", "rahul", "surya"};
TextUtils.join(",",name)
Basic improvements
- Instead of setting the size of the int array to 10, it would be better to derive the right size from the size of String array
- Instead of
int number[]the more conventional way to write isint[] number - For structures that contain multiple values it's more natural to give plural names, for example "number" -> "numbers" for an array of numbers
- The variable names are very poor in general, and should be improved to better reflect their purpose, making the code easier to understand
Something like this:
String line = "1,2,3,1,2,2,1,2,3,";
String[] parts = line.split(",");
int[] ints = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
ints[i] = Integer.parseInt(parts[i]);
}
Split to logical steps
It's good to get into the habit of decomposing tasks to their small steps. That is, instead of having all the logical steps in a single main method, it would be better to split to multiple functions, for example:
static int[] toIntArray(String[] arr) {
int[] ints = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
ints[i] = Integer.parseInt(arr[i]);
}
return ints;
}
static int[] parseLineToIntArray(String line) {
return toIntArray(line.split(","));
}
public static void main(String[] args) {
String line = "1,2,3,1,2,2,1,2,3,";
System.out.println(Arrays.toString(parseLineToIntArray(line)));
}
You code is not properly indented and IMO your comments don't add any value. You could create a separate function instead of putting everything in the main function. Also you could add an extra parameter so you can specify the delimiter instead of always being ",".
Also if you can use java 8 this becomes even more trivial:
public static int[] toIntArray(String input, String delimiter) {
return Arrays.stream(input.split(delimiter))
.mapToInt(Integer::parseInt)
.toArray();
}
If you're using Java 8, you can:
int[] numbers = Arrays.asList(numbersArray.split(",")).stream()
.map(String::trim)
.mapToInt(Integer::parseInt).toArray();
If not, I think your approach is the best option available.
Using java 8 Streams:
List<Integer> longIds = Stream.of(commaSeperatedString.split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
You don't need outer stream. Also return type of Integer.valueOf is already Integer (it is Integer.parseInt which returns int) so you don't even need to boxed() it. Simply use map instead of mapToInt.
Integer[] array = Arrays.stream(" 1,2, 3, 4".split(","))
.map(String::trim)
.map(Integer::valueOf)
.toArray(Integer[]::new);
System.out.println(Arrays.toString(array));
Output: [1, 2, 3, 4]
Another version looks like follows:
Integer[] statusCodes = Stream.of(statusText.split(",")).map(Integer::valueOf).toArray(Integer[]::new);
Java 8 streams offer a nice and clean solution:
String line = "1,2,3,1,2,2,1,2,3,";
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
Edit: Since you asked for Java 7 - what you do is already pretty good, I changed just one detail. You should initialize the array with inputNumber.length so your code does not break if the input String changes.
Edit2: I also changed the naming a bit to make the code clearer.
String line = "1,2,3,1,2,2,1,2,3,";
String[] tokens = line.split(",");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Integer.parseInt(tokens[i]);
}
By doing it in Java 7, you can get the String array first, then convert it to int array:
String[] tokens = line.split(",");
int[] nums = new int[tokens.length];
for(int x=0; x<tokens.length; x++)
nums[x] = Integer.parseInt(tokens[x]);