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?
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.
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(",")));
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With