Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Comma Separated Values to List<Long>

Tags:

Assume I have a set of numbers like 1,2,3,4,5,6,7 input as a single String. I would like to convert those numbers to a List of Long objects ie List<Long>.

Can anyone recommend the easiest method?

like image 777
Kathir Avatar asked Jun 15 '12 14:06

Kathir


People also ask

How do you convert a comma separated string to an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


2 Answers

You mean something like this?

String numbers = "1,2,3,4,5,6,7";  List<Long> list = new ArrayList<Long>(); for (String s : numbers.split(","))     list.add(Long.parseLong(s));  System.out.println(list); 

Since Java 8 you can rewrite it as

List<Long> list = Stream.of(numbers.split(","))         .map(Long::parseLong)         .collect(Collectors.toList()); 

Little shorter versions if you want to get List<String>

List<String> fixedSizeList = Arrays.asList(numbers.split(",")); List<String> resizableList = new ArrayList<>(fixedSizeList); 

or one-liner

List<String> list = new ArrayList<>(Arrays.asList(numbers.split(","))); 
like image 197
Pshemo Avatar answered Sep 29 '22 08:09

Pshemo


Simple and handy solution using java-8 (for the sake of completion of the thread):

String str = "1,2,3,4,5,6,7"; List<Long> list = Arrays.stream(str.split(",")).map(Long::parseLong).collect(Collectors.toList()); 
System.out.println(list); 

[1, 2, 3, 4, 5, 6, 7]

Even better, using Pattern.splitAsStream():

Pattern.compile(",").splitAsStream(str).map(Long::parseLong).collect(Collectors‌​.toList()); 
like image 36
Unihedron Avatar answered Sep 29 '22 09:09

Unihedron