I want to decompose a String array into Long array or List. I don't want to use Loop.
Is there any Java Method to do this.
Simplified Eugene answer with Guava library. Since Guava 16.0.
List<Long> longList = Lists.transform(Arrays.asList(stringArray), Longs.stringConverter());
Update: Solution with Java 8, without 3th party libraries:
List<Long> longList = Stream.of(stringArray).map(Long::valueOf).collect(Collectors.toList());
There is no O(1) operation to "convert" a String[]
(with numeric strings) to a long[]
. It will always be O(n), if the loop visible or hidden in some thirdparty method.
If you don't want to "see" the loop, simply implement a method
Long[] pseudoOneStepConversion(numbers);
and implement
privat Long[] pseudoOneStepConversion(String[] numbers) {
Long[] result = new long[numbers.length];
for (int i = 0; i < numbers.length; i++)
result[i] = Long.parseLong(numbers[i]);
return result;
}
We can do it recursively too - it is still O(n), less performant and doesn't look like a loop:
public static void main(String[] args) {
List<Long> target = new ArrayList<Long>();
copy(new String[]{"1", "2", "3"}, target, 0);
System.out.println(target);
}
private static void copy(String[] source, List<Long> target, int index) {
if (index == source.length)
return;
target.add(Long.parseLong(source[index]));
copy(source, target, index+1);
}
Note - because I start getting downvotes for the recursion example: It is purely academic and not inteded for use in production code - thought, that was clear ;)
With a little help of 3rd party libraries you can avoid coding loops in your own code, but there would be a loop somewhere under the hood. For example:
List<String> stringList = Arrays.asList(stringArray);
List<Long> longList = Lists.transform(stringList, new Function<String, Long>() {
public Long apply(String s) {
return Long.valueOf(s);
}
});
Classes Lists and Function are from Guava library.
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