top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Java 17 - Collections Stream API



The Java Stream API is a powerful tool for processing collections of data in a functional and declarative way. Introduced in Java 8, the Stream API provides a fluent and expressive syntax for performing common operations such as filtering, mapping, sorting, and reducing on collections of data.

A stream is a sequence of elements that can be processed in parallel or sequentially. Unlike traditional collections, streams do not store data; they simply provide a view of the data that can be transformed and processed on demand. Stream operations can be performed in a chain, allowing for a natural and expressive coding style.

The Stream API provides a wide variety of functions for processing streams of data, including intermediate functions such as filter(), map(), and sorted(), and terminal functions such as collect(), reduce(), and forEach(). Intermediate functions return a new stream that can be further processed, while terminal functions produce a final result or side effect.

One of the key benefits of the Stream API is its ability to perform operations in a lazy and parallelizable manner. Stream operations can be optimized for parallel execution on multicore processors, providing significant performance benefits for large datasets.

Overall, the Java Stream API is a powerful and versatile tool that can simplify and streamline the processing of collections of data in Java applications. By using the Stream API, you can write concise and readable code that is also highly parallelizable and efficient.






import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("David");
        names.add("Emma");
        names.add("Frank");
        
        // Filtering using filter() function
        List<String> filteredNames = names.stream()
                                          .filter(name -> name.length() == 4)
                                          .collect(Collectors.toList());
        System.out.println("Filtered names: " + filteredNames);
        
        // Mapping using map() function
        List<Integer> nameLengths = names.stream()
                                         .map(name -> name.length())
                                         .collect(Collectors.toList());
        System.out.println("Name lengths: " + nameLengths);
        
        // Sorting using sorted() function
        List<String> sortedNames = names.stream()
                                        .sorted()
                                        .collect(Collectors.toList());
        System.out.println("Sorted names: " + sortedNames);
        
        // Reducing using reduce() functionint totalLength = names.stream()
                               .map(name -> name.length())
                               .reduce(0, (a, b) -> a + b);
        System.out.println("Total length: " + totalLength);
    }
}

Output:


Filtered names: [Alice, Emma]
Name lengths: [5, 3, 7, 5, 4, 5]
Sorted names: [Alice, Bob, Charlie, David, Emma, Frank]
Total length: 30

In this example, we start by creating a list of String called names. We add six elements to the list using the add() method.

We then demonstrate several Stream API functions:

  • filter() function: This function filters the elements of the stream based on a given predicate. In our example, we use the filter() function to create a new list of names that have a length of 4 characters.

  • map() function: This function maps the elements of the stream to a new value based on a given function. In our example, we use the map() function to create a new list of name lengths.

  • sorted() function: This function sorts the elements of the stream in their natural order or a custom order if a Comparator is provided. In our example, we use the sorted() function to create a new list of names in alphabetical order.

  • reduce() function: This function combines the elements of the stream into a single value based on a given binary operator. In our example, we use the reduce() function to calculate the total length of all the names in the list.

Finally, we print out the results using the println() method.

The Stream API is a powerful tool for processing collections of data in a declarative and functional way. It provides a fluent and expressive syntax for performing common operations such as filtering, mapping, sorting, and reducing. By using the Stream API, you can write concise and readable code that is also highly parallelizable and efficient.

23 views

Recent Posts

See All

Java 17 :Collections

Java 17 comes with a rich set of collection classes that allow you to store, manipulate and retrieve data efficiently. These collection...

Comentarios


bottom of page