Program to Convert Fahrenheit into Celsius Using Java 8

Learn how to convert Fahrenheit into Celsius using Java 8 DoubleStream and map() method with an example.

Code Explanation (Step-by-Step)

• Create a Scanner object to read input from the keyboard.
• Use nextDouble() to read the Fahrenheit temperature entered by the user.
• Use DoubleStream.of() to create a stream containing the Fahrenheit value.
• Apply the map() method to convert the temperature from Fahrenheit to Celsius.
• Method ((r – 32) * 5) / 9 to calculate the Celsius temperature.
• Use forEach() to print the converted Celsius value.
• Close the Scanner object using close().

				
					import java.util.Scanner;
import java.util.stream.DoubleStream;

public class Hello {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter temperature in Fahrenheit: ");
        double fahrenheit = input.nextDouble();

        DoubleStream celsius = DoubleStream.of(fahrenheit)
                .map(r -> ((r - 32) * 5) / 9);

        celsius.forEach(System.out::println);

        input.close();
    }
}
				
			

Output :
Enter temperature in Fahrenheit:
50
10.0

java 8 Program to Convert Fahrenheit into Celsius

				
					import java.util.Scanner;
import java.util.function.DoubleUnaryOperator;
import java.util.stream.DoubleStream;

public class FahrenheitToCelsius {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter temperature in Fahrenheit:");
        double fahrenheit = sc.nextDouble();

        DoubleUnaryOperator convert = f -> ((f - 32) * 5) / 9;

        DoubleStream.of(fahrenheit)
                .map(convert)
                .forEach(c -> System.out.println("Celsius: " + c));

        sc.close();
    }
}
				
			

FAQ
Which Java 8 Stream is used in this program?
DoubleStream is used because the temperature contains decimal values.
Why is map() used?
The map() method transforms the Fahrenheit value into its corresponding Celsius value.
What does DoubleStream.of() do?
It creates a stream containing the specified double value.
What is the Celsius value of 50°F?
10.0°C
What is the formula for converting Fahrenheit to Celsius?
Celsius = ((Fahrenheit – 32) × 5) / 9