You are currently viewing Mastering Java Stream API with Examples

Mastering Java Stream API with Examples

  • Post author:
  • Post category:Java
  • Post comments:0 Comments
  • Post last modified:April 27, 2024

Java Stream API offers a concise and powerful way to process collections of objects in a functional style. Streams enable you to perform various aggregate operations such as filtering, mapping, sorting, and more. In this tutorial, we’ll delve into some of the most commonly used functions in the Java Stream API, accompanied by examples.

1. filter()

The filter() function is used to select elements from a stream based on a specified predicate.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> evenNumbers = numbers.stream()
                                  .filter(n -> n % 2 == 0)
                                  .collect(Collectors.toList());

// Output: [2, 4]

2. map()

The map() function transforms each element of the stream by applying a specified function.

Example:

List<String> names = Arrays.asList("John", "Alice", "Bob");

List<String> upperCaseNames = names.stream()
                                  .map(String::toUpperCase)
                                  .collect(Collectors.toList());

// Output: [JOHN, ALICE, BOB]

3. flatMap()

The flatMap() function flattens a stream of collections into a single stream.

Example:

List<List<Integer>> nestedList = Arrays.asList(
    Arrays.asList(1, 2, 3),
    Arrays.asList(4, 5, 6),
    Arrays.asList(7, 8, 9)
);

List<Integer> flattenedList = nestedList.stream()
                                       .flatMap(Collection::stream)
                                       .collect(Collectors.toList());

// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

4. forEach()

The forEach() function executes a specified action for each element of the stream.

Example:

List<String> names = Arrays.asList("John", "Alice", "Bob");

names.stream()
     .forEach(System.out::println);

// Output:
// John
// Alice
// Bob

5. sorted()

The sorted() function sorts the elements of the stream.

Example:

List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);

List<Integer> sortedNumbers = numbers.stream()
                                    .sorted()
                                    .collect(Collectors.toList());

// Output: [1, 1, 2, 3, 4, 5, 6, 9]

6. collect()

The collect() function accumulates the elements of the stream into a collection.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Set<Integer> evenNumbersSet = numbers.stream()
                                    .filter(n -> n % 2 == 0)
                                    .collect(Collectors.toSet());

// Output: [2, 4]

7. reduce()

The reduce() function performs a reduction operation on the elements of the stream.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int sum = numbers.stream()
                 .reduce(0, Integer::sum);

// Output: 15

8. findFirst() and findAny()

These functions are used to find the first or any element of the stream.

Example:

List<String> names = Arrays.asList("John", "Alice", "Bob");

Optional<String> firstElement = names.stream()
                                    .findFirst();

// Output: John

9. anyMatch(), allMatch(), and noneMatch()

These functions check if any, all, or none of the elements in the stream match a given predicate.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

boolean anyEven = numbers.stream().anyMatch(n -> n % 2 == 0); // true

10. count()

The count() function returns the count of elements in the stream.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

long count = numbers.stream().count(); // 5

:

11. distinct()

The distinct() function returns a stream of unique elements.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 5);

List<Integer> distinctNumbers = numbers.stream()
                                      .distinct()
                                      .collect(Collectors.toList());

// Output: [1, 2, 3, 4, 5]

12. limit() and skip()

These functions limit or skip elements in a stream.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> limited = numbers.stream()
                              .limit(3)
                              .collect(Collectors.toList()); // [1, 2, 3]

List<Integer> skipped = numbers.stream()
                               .skip(2)
                               .collect(Collectors.toList()); // [3, 4, 5]

13. max() and min()

These functions find the maximum or minimum element in a stream.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Optional<Integer> max = numbers.stream().max(Comparator.naturalOrder()); // 5
Optional<Integer> min = numbers.stream().min(Comparator.naturalOrder()); // 1

14. toArray()

The toArray() function converts a stream into an array.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Integer[] array = numbers.stream().toArray(Integer[]::new);

15. forEachOrdered()

The forEachOrdered() function ensures that elements are processed in encounter order.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

numbers.stream().forEachOrdered(System.out::println); // 1 2 3 4 5

Conclusion

These additional functions provide further versatility and functionality when working with Java Streams. By mastering these functions, you can efficiently manipulate and process data in your Java applications. Experiment with these functions in various contexts to fully leverage the power of the Java Stream API.

Leave a Reply