Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decompose a String into Array of Long or List of Long without Loop in JAVA

Tags:

java

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.

like image 411
Lalit Bhudiya Avatar asked Apr 03 '12 13:04

Lalit Bhudiya


3 Answers

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());
like image 80
vklidu Avatar answered Oct 21 '22 15:10

vklidu


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 ;)

like image 25
Andreas Dolk Avatar answered Oct 21 '22 15:10

Andreas Dolk


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.

like image 4
Eugene Kuleshov Avatar answered Oct 21 '22 14:10

Eugene Kuleshov