Reputation: 527
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?
Upvotes: 25
Views: 49939
Reputation: 124265
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:
String#trim
on those individual elements before parsing like Long.parseLong(s.trim())
,
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)Upvotes: 69
Reputation: 5721
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());
Upvotes: 1
Reputation: 28885
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().
Upvotes: 0
Reputation: 11051
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);
Upvotes: 2
Reputation: 11051
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());
Upvotes: 12
Reputation: 5220
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
}
}
Upvotes: 3
Reputation: 898
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 );
Upvotes: -14