Stream mapToDouble() in Java with ExamplesIn Java, the mapToDouble() method is one of the members of the Stream interface which was introduced in Java 8. It converts the elements of a stream into primitive double values by applying a given ToDoubleFunction to each element, this provides an efficient way of converting the stream elements into a specialized DoubleStream. Method SignatureDoubleStream: It is the return type of mapToDouble(). It is the specialized stream for dealing with primitive double type values. mapToDouble: It is the name of the method. ToDoubleFunction<? super T> mapper: It is a functional interface that is a part of Java?s util package and is used as a parameter for various Stream methods. ToDoubleFunction: Represents a function that produces a double-valued result. <? super T>: It denotes a wildcard (?) that stands for any superclass of T. It ensures flexibility in accepting elements that are instances of T or any superclass of T. The mapper function specified (ToDoubleFunction) is applied to each element of the stream. It converts each element to a double value as specified by the function. Example 1: Converting Stream of Integers to DoubleStreamIn this example, we create a stream of Integer values containing 1, 2, 3, 4, 5. The integerStream.mapToDouble(i -> i * 1.5) is used to transform each integer (i) from integerStream into a double value. The i -> i * 1.5 is a lambda expression that defines the transformation multiplying each integer by 1.5. The result is a DoubleStream (doubleStream) that contains the transformed values (1.5, 3.0, 4.5, 6.0, 7.5). Filename: MapToDoubleExample.java Output: Original Values: [1, 2, 3, 4, 5] Transformed Values: [1.5, 3.0, 4.5, 6.0, 7.5] Example 2: Calculating Average of Integer StreamIn this example, the IntStream.rangeClosed(1, 10) creates an IntStream that includes integers from 1 to 10 (inclusive). The filter(i -> i % 2 != 0) filters out even numbers (i % 2 != 0 checks if i is odd) it also ensures that only odd numbers are considered for calculating the average. The mapToDouble(i -> i) maps each remaining integer to a double value. The average() calculates the average of the double values in the stream. Filename: AverageExample.java Output: Average of odd numbers: 5.0 Example 3: Mapping String Lengths to DoubleStreamIn this example, we will create a stream of strings containing "apple", "banana", "cherry", "date", and "elderberry". The filter(s -> s.length() > 5) filters out strings with lengths greater than 5 characters. The mapToDouble(s -> s.length()) maps each remaining string to its length as a double value. Filename: StringLengthMapToDoubleExample.java Output: String: banana String length as double: 6.0 String: cherry String length as double: 6.0 String: elderberry String length as double: 10.0 Example 4: Filtering Numbers Conditionally with Multiple SetsIn this example, we will create two lists named list1 and list2. Then we convert the lists into streams, the mapToDouble(num -> Double.parseDouble(num)) converts each string in the stream to a double using Double.parseDouble(). The filter(num -> (num * num) * 2 == 800) in the example 1 and filter(num -> (num * num) * 2 == 242) in the example 2 filters the stream based on the condition where the square of the number multiplied by 2 equals 800 and 242 in the examples. The forEach(System.out::println) prints each filtered number. Filename: NumberFilterExample.java Output: First set of numbers: 20.0 Second set of numbers: 11.0 Example 5: Computing Square of String LengthsIn this example, we will create two lists named list1 and list2. Then we convert the lists into streams, the mapToDouble(str -> str.length() * str.length()) maps each string to the square of its length as a double. The forEach(System.out::println) prints each computed square value. Filename: StringLengthSquareExample.java Output: Example 1: 25.0 64.0 49.0 25.0 81.0 Example 6: Calculating BMI (Body Mass Index)In this example, we will create a list of Person objects with different attributes. Stream Processing: The mapToDouble(person -> person.getWeight() / (person.getHeight() * person.getHeight())) calculates the BMI for each person using their weight divided by the square of their height (BMI formula). Then forEach(bmi -> System.out.println("BMI: " + bmi)) prints the BMI for each person. Filename: BMICalculatorExample.java Output: BMI Results: BMI: 20.20 BMI: 22.09 BMI: 27.04 BMI: 17.58 Applications1. Financial Data AnalysisIn finance, analyzing transaction data or stock prices often involves processing large datasets to derive meaningful insights. For example, mapping transaction amounts to a DoubleStream and calculating various statistics like averages or totals can provide crucial financial insights. 2. Data Processing in IoT DevicesIn Internet of Things (IoT) applications, devices often generate streams of sensor data. Java streams can be employed to filter, aggregate, or analyze this data in real-time. For instance, processing sensor readings to detect anomalies, computing averages, or predicting trends based on historical data are common tasks where streams excel. 3. Scientific Research and Data AnalysisIn scientific research, analyzing experimental data or simulations often requires processing large datasets efficiently. Java streams can handle tasks such as mapping experimental results to numeric values, filtering outliers, or computing statistical measures across multiple experiments. This approach supports reproducible research and data-driven decision-making. 4. E-commerce and Customer AnalyticsE-commerce platforms can use streams to analyze customer behavior, such as purchase patterns, browsing history, or product preferences. Mapping and aggregating customer data can provide insights into customer segments, trends in purchasing behavior, or popular products. This information is vital for personalized marketing strategies and inventory management. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India