1

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?

5
  • Wait, do you mean convert it to an array of BigIntegers where each int is converted to 1 BigInteger ? Commented Mar 3, 2016 at 12:30
  • Are you just looking for a one-liner or do you feel that you have to save the cost for the iteration? Commented Mar 3, 2016 at 12:30
  • 1
    You will need iteration. No escape from that AFAIK Commented Mar 3, 2016 at 12:31
  • I would like to convert in such a way that each int value is converted to BigInteger value.And yes ,I'm trying to do this to save the cost for iteration. Commented Mar 3, 2016 at 12:34
  • The cost of the iteration will be incurred, no matter what. If not your code then some other (library) code will have to iterate over the array of ints and create the BigInteger instances. Commented Mar 3, 2016 at 12:40

2 Answers 2

5

This should do the job if you're using

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]
Sign up to request clarification or add additional context in comments.

2 Comments

@YassinHajaj the line toArray(BigInteger[]::new) that you had previously did work and was in my opinion cleaner. Still, it works, +1.
@Jean-FrançoisSavard Yes, changing it :)
0

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 byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.