How to Mapping code logic using Stream API
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 :
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;
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");
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);
Finally, you can collect the transformed stream back into a list or another collection:
List upperCaseNameList = upperCaseNames.collect(Collectors.toList());
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.
How to Develop code logic using Stream API Workflow
Let's begin by defining the term stream as it applies to the stream API:
A stream operates on a data source, such as an array or a collection. A stream, itself, never provides storage on a data. It simply moves data, possibly filtering, sorting, or otherwise operating on that data is the process. as a genral rule, however a stream operation by itself does not modyfy the data source. For Example: sorting a stream does not change the order of the source. Rather, sorting a stream results in the creation of a new stream that produces the sroted result.
A Simple Stream Example : Let's work through an example that uses streams. The following program creates an ArrayList called myList that holds a collection of integers. Next, it obtains a stream that uses myList as a source.
OUTPUT:
A stream operates on a data source, such as an array or a collection. A stream, itself, never provides storage on a data. It simply moves data, possibly filtering, sorting, or otherwise operating on that data is the process. as a genral rule, however a stream operation by itself does not modyfy the data source. For Example: sorting a stream does not change the order of the source. Rather, sorting a stream results in the creation of a new stream that produces the sroted result.
A Simple Stream Example : Let's work through an example that uses streams. The following program creates an ArrayList called myList that holds a collection of integers. Next, it obtains a stream that uses myList as a source.
OUTPUT:
Subscribe to:
Posts
(
Atom
)