Powered by Blogger.

How to Mapping code logic using Stream API

No comments :
Stream API in Java provides a powerful way to work with collections and other data sources. Mapping is one of the key operations available in the Stream API, used to transform elements of a stream. Here's a step-by-step guide on how to use the map function with the Stream API:
Import Required Classes :

First, make sure to import the necessary classes:
import java.util.Arrays;
import java.util.List; 
import java.util.stream.Collectors; 
import java.util.stream.Stream;

Create a Stream:
You can create a stream from various sources, like collections, arrays, or generator functions. For example, creating a stream from a list:
List names = Arrays.asList("a14mk", "manoj", "Jack"); 
Stream nameStream = names.stream();
Apply the map Function:
Use the map function to transform each element of the stream. For instance, to convert each name to uppercase:
Stream upperCaseNames = nameStream.map(String::toUpperCase);
Collect the Results:
Finally, you can collect the transformed stream back into a list or another collection:
List upperCaseNameList = upperCaseNames.collect(Collectors.toList());
Complete Example:
Here’s a complete example demonstrating how to use the map function with the Stream API:

Mapping with Complex Objects:
If you are working with a list of objects, you can use the map function to transform specific fields or create new objects. For example:

In this example, the map function is used to extract the names from a list of Person objects.

No comments :

Post a Comment

Please Write a Message for Programming or something Related issues.