In this tutorial, we will see “How to convert Decimal number to Binary using Java 8?”
How to convert decimal number to binary in java 8
Java 8 – How to convert Decimal number to Binary? Click To Tweet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * Using Java 8, Convert Decimal Number to Binary * @author Deepak Verma * */ import java.util.stream.IntStream; public class Convert_Decimal_Number_To_Binary_Java8_Example { public static void main(String[] args) { int decimalNumber = 100; String binaryValue = IntStream.iterate(decimalNumber, a -> a / 2) .limit(32) .map(b -> b % 2) .mapToObj(String::valueOf) .reduce("", (x, y) -> y + x); System.out.println("The Binary value of " + decimalNumber + " is: " + binaryValue); } } |
Output:
1 | The Binary value of 100 is: 00000000000000000000000001100100 |
How to convert decimal number to binary in java 8
In the above example, It uses IntStream and using it’s iterate
method to repeatedly divide the decimal number by number 2, until the result of the division becomes 0. Then, the limit
method is used to limit the number of iterations to 32, which is basically the number of bits in an int
. After that, map
method is used to get the remainder of each division, which is basically the binary digit at that place. After applying map method, now it comes to apply the mapToObj
method to convert each binary digit to a string, and finally, it’s the reduce
method which is used to concatenate all the binary digits into a single string. And, Then using sysout method, we are printing the resulting binary string to the console.
How to convert decimal number to binary in java 8
Java 8 – How to convert Decimal number to Binary? Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: