23

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?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Kathir
  • 497
  • 2
  • 6
  • 14

7 Answers7

66

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(",")));




Bonus info:

If your data may be in form like String data = "1, 2 , 3,4"; where comma is surrounded by some whitespaces, the split(",") will produce as result array like ["1", " 2 ", " 3", "4"].

As you see second and third element in that array contains those extra spaces: " 2 ", " 3" which would cause Long.parseLong to throw NumberFormatException (since space is not proper numerical value).

Solution here is either:

  • using String#trim on those individual elements before parsing like Long.parseLong(s.trim())
  • consuming those extra whitespace along , while splitting. To do that we can use split("\\s*,\\s*") where
    • \s (written as "\\s" in string literals) represents whitespace
    • * is quantifier representing zero or more so "\\s*" represents zero or more whitespaces (in other words makes it optional)
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 1
    This answer is super old, but still relevant and should be the accepted answer. – cautionbug May 18 '21 at 16:14
  • Adding one slight change, `String numbers = "1,2,3,4,5,6,7"; List list = new ArrayList(); for (String s : numbers.split(",")) list.add(Long.parseLong(s.trim())); System.out.println(list);` Added _s.trim()_ so that if there is a string like, "1, 2", it does not throw a `NumberFormatException` for string " 2". – Vicky Singh Jan 13 '23 at 11:36
  • @VickySingh Alternative since `split` supports *regex* we can use `split("\\s*,\\s*)` instead of `split(",")` to split on *comma with possible whitespaces surrounding it*. – Pshemo Jan 13 '23 at 12:19
12

Simple and handy solution using (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());
Unihedron
  • 10,902
  • 13
  • 62
  • 72
3
String input = "1,2,3,4,5,6,7";
String[] numbers = input.split("\\,");
List<Integer> result = new ArrayList<Integer>();
for(String number : numbers) {
    try {
        result.add(Integer.parseInt(number.trim()));
    } catch(Exception e) {
        // log about conversion error
    }
}
alexey28
  • 5,170
  • 1
  • 20
  • 25
  • Is there is any utility method availalble in java or apache commons or any other to get the results in a simple way by calling a method? – Kathir Jun 15 '12 at 14:30
  • You can use some appache or guava collections based on visitor pattern to convert String to Integer, but it will not make code simple. It will make it is harder to read. – alexey28 Jun 15 '12 at 14:34
2

You can use String.split() and Long.valueOf():

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

System.out.println(list);
Jonathan
  • 20,053
  • 6
  • 63
  • 70
Unihedron
  • 10,902
  • 13
  • 62
  • 72
1

If you're not on java8 and don't want to use loops, then you can use Guava

List<Long> longValues = Lists.transform(Arrays.asList(numbersArray.split(",")), new Function<String, Long>() {
                @Override
                public Long apply(String input) {
                    return Long.parseLong(input.trim());
                }
            });

As others have mentioned for Java8 you can use Streams.

List<Long> numbers = Arrays.asList(numbersArray.split(","))
                      .stream()
                      .map(String::trim)
                      .map(Long::parseLong)
                      .collect(Collectors.toList());
codersl
  • 2,222
  • 4
  • 30
  • 33
Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52
0

I've used the following recently:

import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
...

    final ImmutableList<Long> result = Splitter.on(",")
        .trimResults()
        .omitEmptyStrings()
        .splitToStream(value)
        .map(Long::valueOf)
        .collect(toImmutableList());

This uses Splitter from Guava (to handle empty strings and whitespaces) and does not use the surprising String.split().

palacsint
  • 28,416
  • 10
  • 82
  • 109
-14

I would use the excellent google's Guava library to do it. String.split can cause many troubles.

String numbers="1,2,3,4,5,6,7";
Iterable<String> splitIterator = Splitter.on(',').split(numbers);
List<String> list= Lists.newArrayList(splitIterator );
jocelyn
  • 788
  • 6
  • 12