Code

Java Stream API: Usage Examples

Java Stream API: Usage Examples

Learn: The Java Developer Profession

Learn More

In this article, we'll focus on the practical application of streams, avoiding unnecessary theory. We'll cover seven common scenarios where using streams brings significant benefits. We'll also compare it to traditional imperative approaches to clearly demonstrate the effectiveness of streams in various situations.

Stream API - What is it?

This method allows you to effectively interact with data structures in Java, especially collections, using functional programming principles. A functional approach promotes cleaner and more understandable code, simplifying data manipulation and increasing program readability. Functional programming and the use of lambda expressions in Java have become important aspects of modern programming. These concepts allow for more concise and expressive code, improving the readability and maintainability of applications. In this article, we'll cover the basic principles of functional programming and their implementation in Java, including examples of lambda expressions. Learn how these tools can significantly simplify your work and improve the efficiency of software development. Read on to dive into the world of functional programming and master lambdas in Java. A stream is a tool for general-purpose data processing. It's not a new data structure, but rather a mechanism that uses existing collections to extract new elements. Streams allow for efficient data processing and transformation, simplifying manipulation of large amounts of information. This approach allows developers to optimize code, improving its readability and performance. Streams are becoming increasingly popular in modern programming languages ​​like Java and Python, making them an essential element for working with data.

Various methods available in the Stream interface are available for data processing. These methods enable standard collection operations such as sorting, rearranging, and filtering. We'll explore some of these methods in more detail later.

Think of a stream as a continuous stream of data, and the chain of method calls as a pipeline that processes this data. This approach allows you to efficiently manage data processing, ensuring a fast and organized process.

Each intermediate method receives the result of the previous step, represented as a stream, as input. It performs a specific portion of the work and returns a new stream. This approach enables sequential data processing, providing modularity and ease of use when working with data streams.

The final (terminal) method may return void or return a result that differs from the stream type.

Streams allow programmers to avoid writing repetitive code when working with collections. Using streams, developers can focus on application logic without delving into implementation details. This significantly simplifies data processing and improves code readability. Streams optimize work with sets of elements, allowing operations to be performed more efficiently and declaratively.

There are other advantages as well:

  • Streams support one of the fundamental principles of good design—low coupling. The less a class knows about other classes, the better. The sorting algorithm shouldn't care what exactly it's sorting. This is what streams do.
  • With streams, operations on collections are easier to parallelize: with an imperative approach, this would require at least one more cycle.
  • Streams reduce the number of side effects: Stream API methods do not modify the source collections.
  • With the Stream API, complex data processing algorithms are concisely written.

Now that you are close to seeing the benefits of streaming, let's move on to the practical aspects. Streams are a powerful tool for interacting with an audience and creating unique content. They allow you not only to share knowledge and experience, but also to build a community around your brand. Dive into the world of streaming, explore platforms like Twitch or YouTube, and start broadcasting. Effective streaming practice will help you establish a strong connection with your viewers and increase the visibility of your content online.

Think of a stream as a data stream, and a chain of method calls as a pipeline. This approach enables efficient data processing and transformation, ensuring high performance and flexibility in software development. Streams provide continuous data processing, while pipelines help organize a sequence of operations, making the application more structured and easier to maintain.

Each intermediate method receives the result of the previous stage, represented as a stream. It performs its specific task and returns a new stream, which is passed to the next method. This approach ensures modularity and simplifies data processing, allowing for efficient management of information flows.

The last or terminal method in programming may return no value (void) or return a result other than a stream.

Preparing the Data

The Java Stream API methods will be demonstrated using an offline library example. In this library, such data as the author, title, and year of publication are available for each book. Using the Java Stream API, you can efficiently process and analyze book data, which will simplify various operations such as filtering, sorting, and aggregating information. This approach significantly improves the performance and readability of the code, making it more understandable and easier to maintain.

In our library, we will store information about readers, including their last name, first name, patronymic, and email address. Each reader has the opportunity to take one or more books from the library, information about which will also be stored in our database. This will allow us to effectively manage book lending and maintain communication with readers.

To effectively communicate with readers, it is necessary to obtain their consent to email notifications. The library will send newsletters containing reminders about book return deadlines, as well as current news and events. This will help us maintain communication with users and improve their service experience.

The Java code example demonstrates its syntax and basic programming principles. Java is a high-level, object-oriented language that is widely used to develop a variety of applications, from mobile to web services. In this example, you will see how to create classes, methods, and use the basic language constructs. Java provides platform independence, making it an ideal choice for developing software that must run on various operating systems.

Here is a simple Java code example illustrating the creation of a class and a method that displays a message on the screen.

«`java
public class HelloWorld {
public static void main(String[] args) {
System.out.println(«Hello, world!»);
}
}
«`

This example creates a `HelloWorld` class and prints the text «Hello, world!» in the `main` method. This code is a basic example of using Java and is suitable for beginning programmers who want to learn the basics of the language. Java offers powerful tools and libraries that enable you to create scalable and secure applications, making it one of the most popular programming languages ​​in the world.

For Sorting — sorted()

This method is designed to sort elements in a stream. By default, elements are sorted in ascending order. For numeric values, sorting is intuitive; however, it should be noted that uppercase and lowercase letters are processed separately, which can affect the sorting result. This is important to consider when working with text data to achieve the expected order of elements.

It is important to note that this method is intended exclusively for sorting objects that implement the Comparable interface. Using this interface allows you to establish a natural sorting order for objects, which is a key aspect when working with data collections. Sorting using the Comparable interface simplifies the process of comparing objects and improves the efficiency of sorting algorithms.

If object classes do not implement this interface or custom sorting logic is required, you can pass your own element comparison algorithm as an argument. This allows for flexible customization of the sorting process and adaptation to specific tasks, thereby ensuring maximum efficiency and ease of use of data.

Using this method generates a new data stream.

Get a complete list of library books, sorted by year of publication. This will allow you to easily find literature by publication date and track changes in themes and genres of books over the years. Explore the archive and select works that interest you to deepen your knowledge or find inspiration in literature.

The List interface offers a method for sorting elements—sort(). This method allows you to pass a comparison algorithm that determines the sorting order. Before lambda expressions, developers created their own classes implementing the Comparator interface or used anonymous classes to define comparison logic. Using lambdas, the sorting process became simpler and clearer, significantly simplifying the code and improving its readability.

The sort() method does not return a result, but modifies the original collection. In this example, sorting must be moved to a separate method to preserve the current order of the books. This avoids unwanted changes to the original collection and provides more flexible data management. Sorting in a separate method simplifies working with the collection and makes the code more understandable and convenient for further manipulation.

The Comparator.comparing(Book::getIssueYear) lambda expression is used to pass the element comparison algorithm to the sorted() method. This approach allows for convenient sorting of Book class objects by publication year. Using lambda expressions in Java simplifies the creation of comparators and makes the code more readable. Sorting by publication year can be useful in various applications, such as libraries or bookstores, where the order of publications is important.

This is similar to the anonymous class in the example above: it means that books are compared based on their publication year.

The collect(Collectors.toList()) method finalizes the stream and converts its elements to a List. This method is an important part of the Java Stream API, allowing you to efficiently collect data from a stream into a manageable structure. Using collect(Collectors.toList()) not only simplifies data processing but also improves application performance by optimizing collection handling.

There was no need to create a separate method for sorting, which made the code more compact and simplified. This approach improves the readability and maintainability of the code, which is an important aspect in software development.

For transformation — map()

The object transformation method is used for various tasks, including extracting the values ​​of individual fields or creating new objects based on the data of the original object. This process allows for efficient processing and adaptation of data, which provides flexibility in working with different types of information. Object transformation is an important aspect of development, as it helps optimize code and improve the data structure.

We need to create a mailing list including the email addresses of all library readers. We will not take into account the consent flag for receiving information, since the library is closing, and we want to notify everyone of this event.

In this example, we use a loop to iterate, simultaneously changing an instance of the new list. If there is a need to set filter conditions, the design will become even more complex.

The first time we use the map() function, we extract email addresses from the list of readers. Then, in the next step, we create instances of the EmailAddress class and collect the obtained addresses in a common list. This allows you to efficiently manage and process email addresses, which is especially important for mailing list sending systems and working with customer databases.

For filtering — filter()

The method filters the data stream according to the specified predicate. This allows you to formulate the condition in a compact form, avoiding complex if-else constructions.

To form a mailing list, you need to consider only those addresses of readers who have agreed to receive information. It is also important to ensure that these readers have borrowed more than one book from the library. This will create a target audience interested in receiving the newsletter and increase the effectiveness of communication.

In this context, additional conditions are added to the loop that will be checked for each reader. This allows us to more precisely customize the data processing logic, ensuring an individual approach to each user.

In the first stage, using the filter() function, we reduce the number of readers, focusing on the list of users who agreed to receive the newsletter. This allows us to optimize the process of interaction with the audience and increase the effectiveness of communication.

In the second stage, we select those who have read more than one book from the total number of readers.

Using the map() and collect() functions, we extract email addresses, convert them to the required format and form a list from them. This process allows us to efficiently process data and obtain a structured result for further use.

For transformation and creation of a linear list — flatMap()

The flatMap() method performs its work in two stages, which is reflected in its name. It combines two main operations: first, the transformation of elements, and then the “flattening” of the data structure. First, each element of the source array is transformed using the given function, and then all the resulting arrays are combined into a single array. This method is especially useful when working with nested data structures, as it allows you to simplify and make the code more readable. Using flatMap() optimizes the data processing process, minimizing the number of steps and simplifying the logic of array manipulation.

  • map (we already know that this is a transformation);
  • and flat - literally "flat".

When using the map() function to process a stream of lists, the result will be a stream containing lists within lists, that is, List>. This behavior is due to the fact that map() applies the given function to each element of the source stream, in this case, to lists. Thus, the output structure is one in which each element is a list, which may require additional processing to obtain a flat list or other desired data structure.

The flatMap() method is used to create a one-dimensional list to which the transformed values ​​from all lists obtained by applying the map() method are sequentially appended. This allows for efficient processing of nested data structures and simplifies working with arrays, providing a more compact and convenient result. Using flatMap() improves code readability and optimizes the data transformation process, which makes it an essential tool in modern programming.

map vs. flatMap

Let's consider a situation when this operation is especially useful.

Make a unique list of all books that have been borrowed by readers. In this list, we need to eliminate duplicates so that each book by the same author with the same title and publication year appears only once.

To obtain a list of unique books, we used the Set data structure. First, we sequentially processed all readers and added their books to this set. Once this process was complete, we converted the set to a list (ArrayList), which allowed us to obtain the final list of unique books.

After using the flatMap() method, we get a stream that contains all books from all readers. The distinct() method allows us to leave only unique values ​​in this stream, which ensures the absence of duplicates. Thus, the combination of flatMap() and distinct() efficiently processes data, allowing us to work with unique records in the book collection.

Process optimization can occur without the need to implement additional fields and loops. This allows us to simplify the structure and increase work efficiency. Eliminating unnecessary elements promotes faster data processing and improves user experience. Using simple and understandable solutions is key in developing effective systems.

To check if there is anything matching, use anyMatch()

A simple method that takes a predicate condition and returns a boolean flag. This method allows you to efficiently check if a certain condition is met, which can be useful in various programming tasks. Using this approach, developers can simplify the decision-making process in the code, providing a cleaner and more understandable structure. The method is based on logical operations, which makes it a universal tool for solving many problems.

  • true if there is an object in the stream that satisfies the condition;
  • false - if there is no such object.

Check if any of the readers of your library have checked out books by George Orwell. It is interesting to know how popular his works are among visitors. Orwell is a significant figure in literature, and his works, such as «1984» and Animal Farm continue to generate interest and discussion. Make sure his books are available in your library to satisfy readers' requests.

Let's create two nested loops and introduce an additional variable to store the intermediate result. The loop will be interrupted the first time we encounter Orwell's work.

The flatMap() method allows us to create a stream that combines all the books into a single whole, and the anyMatch() method checks if Orwell's name is among the authors. This is an effective way of filtering data, allowing you to quickly find the necessary elements in the collection.

To remain only one - reduce()

The reduce() method allows you to convert an array to a single value, reducing it to a single result. To use this method, you must pass the initial value (which is an optional parameter) and an accumulator function that takes two parameters. This function processes each element of the array, sequentially applying the specified logic, making the reduce() method a powerful tool for performing various calculations and aggregating data in JavaScript.

This function is first applied to the initial value and the first element of the data stream. The result of this step is then combined with the next element of the stream, and this continues until all elements have been processed. Thus, the function sequentially processes each element, starting with the initial value, which allows for efficient work with data streams.

More complex reduction methods exist that require the addition of a third parameter—a combination function. This parameter is especially useful in cases where parallelization is required or when the types of the accumulator function arguments do not match the type of the function's result. The combine function allows you to efficiently process data and combine results, which improves performance and makes it easier to work with different types of data.

Calculating the maximum value using reduce()

Of course, I'm ready to help with editing the text. Please provide the source code to be refactored.

Determine the maximum number of books a reader currently has.

At the beginning of the process, we set the minimum number of books each reader has to zero. We then loop through all readers, analyzing the number of books each has, and updating the maximum number of books if necessary. This allows us to determine which readers have the most books, which can be useful for further analysis and recommendations.

In the first step, we use the map() method to map each reader to the number of books they have borrowed. We then use the reduce() method to determine the maximum value in the resulting data stream. This process allows us to effectively analyze reading patterns across users and identify those who have borrowed the most books.

Each call to the accumulator function in JavaScript creates a new object. This is important to consider, especially if you want the result of the reduce() method to be a complex object, such as a collection. In this case, a new collection will be created at each step of the accumulator function. This can lead to inefficient memory usage and reduced performance if the process is not optimized. To avoid unnecessary resource consumption, methods that allow modifying an existing object rather than creating a new one at each step can be used.

The negative impact on performance can be significant. In such situations, it is recommended to use the collect() method, which allows you to optimize data processing and improve the efficiency of the application.

Java developer profession

You will learn Java programming from scratch and create web applications using the Spring framework. In six months, you'll gain fundamental skills and build a portfolio, and we'll help you find a job.

Find out more