I have an int array with me. Is there a way to convert this int array directly to BigInteger Array without iterating through the elements?
2 Answers
This should do the job if you're using java-8
int[] ints = new int[]{1,2,3};
System.out.println(Arrays.toString(ints)); // [1, 2, 3]
BigInteger[] bigs = Arrays.stream(ints)
.mapToObj(BigInteger::valueOf)
.toArray(BigInteger[]::new);
System.out.println(Arrays.toString(bigs)); // [1, 2, 3]
2 Comments
toArray(BigInteger[]::new) that you had previously did work and was in my opinion cleaner. Still, it works, +1.There is no way to accomplish this without iteration under Java-8 (and why does that matter, does the performance hinder your runtime by so much? Is this the bottleneck of your application? You must know that the iteration "cost" will take its toll from your application no matter if you use it directly or not).
Anyway, for the sake of completeness and to make this answer more useful, this is how you might do that:
for (int i = 0; i < arr.length ; i++)
bigIntegerArray[i] = BigInteger.valueOf(arr[i]);
And if you decide you want to convert your int array to a single BigInteger, there is the constructor public BigInteger(byte[] val) that:
Translates a
bytearray containing the two's-complement binary representation of aBigIntegerinto aBigInteger. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.
(And as you probably know int can be represented as 4 bytes)
intis converted to 1BigInteger?