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,601
  • 13
  • 59
  • 69
Kathir
  • 497
  • 2
  • 6
  • 14

7 Answers7

63

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(",")));
codersl
  • 2,144
  • 4
  • 28
  • 32
Pshemo
  • 118,400
  • 24
  • 176
  • 257
11

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,601
  • 13
  • 59
  • 69
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,040
  • 1
  • 19
  • 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
  • 19,557
  • 6
  • 64
  • 67
Unihedron
  • 10,601
  • 13
  • 59
  • 69
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,144
  • 4
  • 28
  • 32
Kishore Bandi
  • 5,237
  • 2
  • 29
  • 47
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
  • 27,430
  • 10
  • 76
  • 108
-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
  • 718
  • 5
  • 12