The Stream API was introduced in Java 8. The Stream in Java is the sequence of objects supporting multiple methods to obtain the required output. These methods are mapping, filtering, etc, and are utilized when needed. Among these Stream API methods, a frequently used method is the map() method which helps us manipulate the streams.
In this article, we will discuss the Stream API’s map() method with the help of different examples.
How to Use/Implement Stream map() Method in Java?
The map() method is considered a functional operation that implements a specific function on all the elements declared in the stream. It returns a transformed stream with different elements. This method in Java is helpful in applications where a single function is to be applied on an entire stream.
Let us first look into the syntax of the Stream map() method then move to the code examples to implement it.
Syntax
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
In the above syntax
- R shows the new stream element.
- Stream is the interface of Java.
- T is known as the type of stream element.
- The mapper function returns a new stream when mapped on each function.
Example 1: Converting UpperCase to LowerCase Using Stream map() Function
The map() method can be implemented to convert the Uppercase to lowcase or vice versa. This method uses certain other methods like toLowercase() for the conversion process as depicted in the code below.
//Import the required Package
import java.util.*;
import java.util.stream.Collectors;
//Declare the class in Java
class StreamExample1{
// main() method
public static void main(String[] args)
{
System.out.println("The Stream is: ");
// Declare the String in the List
List<String> li = Arrays.asList("JAVA", "IS", "FUN", "A", "B", "C");
//stream map() to maps the lowercase
List<String> output = li.stream().map(String::toLowerCase).
collect(Collectors.toList());
//Display the lowercase characters
System.out.println(output);
}
}
In the above Java code:
- The packages required to implement the map() method are imported.
- A class is declared as “StreamExample1”.
- In the next step, an object “li” is created for the list.
- The li.stream().map(String::toLowerCase) method changes the strings from Uppercase to the Lowercase.
- The collect() method of the collector class is used to collect all the new elements into the list.
- The new stream is printed as the output.
Output
In the output below, the stream is printed in Lowercase using the map() method of Stream API in Java.
Example 2: Map a Specific Number on Each Integer in the List
Another implementation of the map() method is that it uses the mapper function declared as “8” in the code below which is applied to all the elements of the stream.
//Import the required Package
import java.util.*;
import java.util.stream.Collectors;
//Declare the class in Java
class StreamExample2{
// main() method
public static void main(String[] args)
{ // Declare the String in the List
List<Integer> li = Arrays.asList(1,2,5,10,15);
System.out.println("The Original List is: " +li);
System.out.println("The List after stream map() function is: ");
//stream map() to maps the lowercase
li.stream().map(number -> number * 8).forEach(System.out::println);
}
}
In the above code:
- The packages required are imported.
- The class is declared as “StreamExample2”.
- A list of integers is declared as “li” using Arrays.asList() method in Java.
- In the last step, the stream().map() method, maps the value of “8” on each and every integer declared in the List and the output gets printed.
Output
The output below shows the results as 8, 16, 40, 80, and 120 respectively when the value of “8” is mapped on all the list elements.
Example 3: Printing the Length of the String Using Stream map(mapper function)
The example below shows how the string is declared and the length of the string is printed using the stream map() method of Java.
//Import the package
import java.util.*;
//Declare the class
class StreamExample3 {
//Main method
public static void main(String[] args)
{
//Declare Strings in a List
List<String> li = Arrays.asList("Java", "is", "a", "Programming", "language");
System.out.println("The List is: " +li);
//the mapper() function of the stream maps the lengths of the strings
System.out.println("The length of each String is: ");
li.stream().map(str -> str.length()).forEach(System.out::println);
}
}
In the code block, the “str.length()” method fetches the length of the declared string implemented along with the li.stream().map() method.
Output
In the output below, the List of strings and the length of each string are printed.
Example 4: Calculate the Average of the Integers in the List
Another application of the map() method is to calculate the average of the integers as depicted in the code below.
//Import the package
import java.util.*;
//Declare the class
class StreamExample4 {
//Main method
public static void main(String[] args)
{
List<String> score = Arrays.asList("70", "85", "68", "90");
//double type
double result = score.stream().mapToInt(Integer::parseInt).average().orElse(0.0);
// Use 0.0 if there are no scores
System.out.println("The Average Score is: " + result);
}
}
In the above code,
- The mapToInt() method converts the string to an integer.
- The next method that is “.average()” calculates the average of the specified integers.
- The last part is “.orElse(0.0)” which returns a value of 0.0 when there are no scores present.
Output
In the output below, the average score is printed as 78.25.
Example 5: Extract the First Two Characters of the String
This example shows how a specified number of characters are abstracted using the map() method in Java.
//Import the Packages required
import java.util.*;
import java.util.stream.Collectors;
//Declare the class
class StreamExample5 {
public static void main(String[] args) {
//The Original List
List<String> list1 = Arrays.asList("Java", "Javascript","HTML");
//Print the Original List
System.out.println("The Original List is: " + list1);
//The stream map() method to abstract 2 characters
List<String> result = list1.stream().map(str -> str.substring(0, 2))
.collect(Collectors.toList());
//Print the output
System.out.println("The List after applying the stream map() method to extract 2 characters is:" + result);
}
}
In the above code,
- The substring() method is used with the stream.map() method to return a part of a certain string.
- To extract the initial two characters from each element of the given list, the “0” and “2” are passed as arguments to the substring() method.
Output
In the code below, the original list, and the initial two characters of each element [Ja, Ja, HT] are printed using the map() method.
This concludes the discussion on the Stream map() method with examples.
Conclusion
The Stream map() method of Java uses the mapper function on all the elements of the stream and returns a new stream. It can be used to calculate the average of the numbers, convert the uppercase strings to lowercase strings, print the length of the strings, and so on. In this article, we have implemented the stream map() method along with different examples.