Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream digits to number

I am struggling to get a functioning code for this. I have a stream of digits between 0 and 9. I want to get a BigInteger out of those digits. Example:

IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.

Is there a way to concatenate all elements out of the stream? Here is my basic idea:

digits.forEach(element -> result=result.concat(result, element.toString()));
like image 789
Daniel Odesser Avatar asked Dec 09 '25 12:12

Daniel Odesser


1 Answers

You could map each digit to a string, join them all together and then create a BigInteger from it:

BigInteger result =
    IntStream.of(1, 2, 3)
             .mapToObj(String::valueOf)
             .collect(Collectors.collectingAndThen(Collectors.joining(), 
                                                    BigInteger::new));
like image 195
Mureinik Avatar answered Dec 12 '25 02:12

Mureinik