1

Is there an elegant, clean way for converting primitive data type double array to OO Double array (e.g. double[] into Double[])?

There are some nice solutions out there, e.g.

int[] intArray = { ... };
Integer[] what = Arrays.stream( intArray ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( intArray ).boxed().toArray( Integer[]::new );

(taken from here), but this requires Java 8. Is there a similar elegant, performant way for Java 7 and below?

Community
  • 1
  • 1
Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
  • 1
    I did some search online couple weeks ago about this and people asked similar questions on SO also, seems like the only way is going through a loop. – OPK Dec 29 '15 at 15:43
  • 1
    can anyone comment on the efficiency when using `stream` with java 8? – OPK Dec 29 '15 at 15:45
  • Probably duplicate of [this post](http://stackoverflow.com/questions/880581/how-to-convert-int-to-integer-in-java) – RPresle Dec 29 '15 at 15:46
  • @RPresle I clearly differentiate to this post; the post has solutions for Java 8, but no non-loop solution for < Java 8. – Michael Dorner Dec 29 '15 at 15:48

1 Answers1

2

If you want a one liner that compiles with Java 7, you can use ArrayUtils from Apache Commons. E.g.

Integer[] what = ArrayUtils.toObject(intArray);

Works for any primitive type. That's probably more "elegant" and "clean" than the Java 8 code you posted. If you want to avoid libraries like Apache Commons, I am afraid you have to use a for loop.

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82