Logo
Unit 13 – Streams API in Java

Streams API in Java

Duration: 7 minutes

Hello, Java developers!

Today, we’ll delve into the Java Streams API, a powerful feature introduced in Java 8. It provides a new abstraction called Stream that lets you process data in a declarative way. The Streams API allows for functional-style operations on streams of elements, such as collections.

Understanding Streams API

Streams represent a sequence of objects from a source, which supports aggregate operations. Key features include:

No storage: A stream does not store data.Functional in nature: Operations on streams do not modify their source.Laziness-seeking: Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, seeking to avoid examining all the data.

Common Stream Operations

filter: Returns a stream with elements that match a given condition.map: Transforms the elements of a stream by applying a specified function.reduce: Performs a reduction on the elements of the stream to produce a single result.Example: Using Streams with Collections

Consider a list of names. We can use stream operations to manipulate these names:

java
Copy code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List names = Arrays.asList("John", "Jane", "Adam", "Tom");
// Filter names that start with 'J'
List namesWithJ = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList());
System.out.println(namesWithJ); // Output: [John, Jane]
// Convert names to uppercase
List uppercaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(uppercaseNames); // Output: [JOHN, JANE, ADAM, TOM]
}
}

Exercise: Perform Operations on Collections Using Streams

Now, it’s your turn to practice:

Start with a collection of integers (e.g., a List).Use stream().filter() to retain only those numbers that are even.Then, use stream().map() to square each number.Finally, use stream().reduce() to sum up all the squared numbers.Conclusion

Excellent work! The Streams API is a powerful tool in Java for processing sequences of data, particularly for collections. It brings functional programming features to Java, enabling operations like map, filter, and reduce to be performed in a clean and concise way.

Experiment with the Streams API to explore more of its capabilities, such as sorted, distinct, or limit operations. This will enhance your skills in writing efficient, readable, and declarative-style Java code.

Happy coding, and enjoy the stream of possibilities with the Java Streams API!

Next Tutorial: Regular Expressions in Java

7 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!