What is JAVA Stream API

Java Stream API is a powerful tool introduced in Java 8 for processing and manipulating collections of data in a functional way. Streams provide a declarative way to perform operations on collections, making code more concise, readable, and maintainable.

Streams are composed of three parts: a source, intermediate operations, and terminal operations. The source is a collection or other data source. Intermediate operations are operations that are performed on the stream before the terminal operation, such as filtering, sorting, or mapping. Terminal operations are operations that end the stream, such as collecting the results into a collection or performing a final computation.

Some of the commonly used methods in the Stream API include filter(), map(), reduce(), collect(), flatMap(), sorted(), and forEach(). These methods can be combined to perform complex operations on collections with just a few lines of code.

Here’s an example of using the Stream API to filter and map a list of integers:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenSquares = numbers.stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * n)
    .collect(Collectors.toList());

In this example, we use the filter() method to select only the even numbers, and the map() method to square them. Finally, we use the collect() method to gather the results into a new list.

The Stream API is a powerful tool for writing concise and expressive code that operates on collections of data. With a little practice, you can quickly become proficient in using streams to perform complex operations on your data.

methods in the Stream API

The Stream API in Java provides a set of methods for performing various operations on streams. Some of the commonly used methods in the Stream API include:

  1. filter(Predicate<T> predicate): This method takes a Predicate function as an argument and returns a new stream consisting of the elements that satisfy the predicate.
  2. map(Function<T,R> mapper): This method takes a Function as an argument and returns a new stream consisting of the results of applying the function to each element of the stream.
  3. flatMap(Function<T,Stream<R>> mapper): This method takes a Function as an argument that returns a stream for each element of the input stream, and returns a new stream consisting of the concatenated output streams.
  4. distinct(): This method returns a new stream with distinct elements based on their natural order or the order determined by a Comparator.
  5. sorted(): This method returns a new stream with the elements sorted in their natural order or the order determined by a Comparator.
  6. peek(Consumer<T> action): This method returns a new stream consisting of the elements of the original stream with a side-effect action performed on each element as they are consumed.
  7. forEach(Consumer<T> action): This method performs the specified action on each element of the stream in iteration order.
  8. reduce(T identity, BinaryOperator<T> accumulator): This method returns the result of applying the binary operator to the elements of the stream, in order, with the given identity as the initial accumulator value.
  9. collect(Collector<T,A,R> collector): This method collects the elements of the stream into a collection using the specified Collector.
  10. count(): This method returns the count of elements in the stream.
  11. anyMatch(Predicate<T> predicate): This method returns true if any element of the stream matches the given predicate.
  12. allMatch(Predicate<T> predicate): This method returns true if all elements of the stream match the given predicate.
  13. noneMatch(Predicate<T> predicate): This method returns true if no elements of the stream match the given predicate.

These are some of the commonly used methods in the Stream API. By using these methods in combination, complex operations can be performed on collections in a concise and efficient manner.

Example for Java stream Filter

List<String> fruits = Arrays.asList("apple", "banana", "kiwi", "orange", "mango");

// Filter out the fruits that start with the letter 'k'
List<String> filteredFruits = fruits.stream()
                                    .filter(fruit -> !fruit.startsWith("k"))
                                    .collect(Collectors.toList());

System.out.println(filteredFruits); // [apple, banana, orange, mango]

Example for Java stream Map

List<String> words = Arrays.asList("hello", "world", "java", "stream", "api");

// Map each word to its length
List<Integer> lengths = words.stream()
                             .map(String::length)
                             .collect(Collectors.toList());

System.out.println(lengths); // [5, 5, 4, 6, 3]

Example for Java stream FlatMap

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

// Flatten the list of lists into a single list
List<Integer> flattened = numbers.stream()
                                  .flatMap(List::stream)
                                  .collect(Collectors.toList());

System.out.println(flattened); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example of using the Stream distinct() method

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

List<Integer> distinctNumbers = numbers.stream()
                                      .distinct()
                                      .collect(Collectors.toList());
                                      
System.out.println(distinctNumbers); // output: [1, 2, 3, 4]

In this example, we have a list of integers with some duplicates. We use the stream() method to create a stream from the list, then call the distinct() method to get a new stream with only distinct elements. Finally, we use the collect() method to gather the distinct elements into a list. The output of the program is [1, 2, 3, 4].

Example of using the Stream sorted() method

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

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

System.out.println(sortedNumbers); // output: [1, 2, 3, 4, 5]

In this example, we have a list of integers that are unsorted. We use the stream() method to create a stream from the list, then call the sorted() method to get a new stream with the elements sorted in their natural order. Finally, we use the collect() method to gather the sorted elements into a list. The output of the program is [1, 2, 3, 4, 5].

Example of using the Java Stream peek() method

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

List<Integer> result = numbers.stream()
                               .peek(n -> System.out.println("Processing number: " + n))
                               .map(n -> n * 2)
                               .peek(n -> System.out.println("Result: " + n))
                               .collect(Collectors.toList());

System.out.println(result); // output: [2, 4, 6, 8, 10]

In this example, we have a list of integers. We use the stream() method to create a stream from the list, then call the peek() method to perform a side-effect operation on each element of the stream. In this case, we print a message indicating that we are processing each number. We then call the map() method to double each number, and call peek() again to print a message indicating the result of the operation. Finally, we use the collect() method to gather the results into a list. The output of the program shows that the side-effect operation was performed for each element of the stream, and the doubled numbers were collected into a list.

Example of using the Java Stream forEach() method

List<String> words = Arrays.asList("hello", "world", "java");

words.stream()
     .forEach(word -> System.out.println(word.toUpperCase()));

// output:
// HELLO
// WORLD
// JAVA

In this example, we have a list of strings. We use the stream() method to create a stream from the list, then call the forEach() method to perform an operation on each element of the stream. In this case, we convert each word to uppercase and print it to the console. The output of the program shows that the operation was performed for each element of the stream

Example of using the Java Stream reduce() method

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

int sum = numbers.stream()
                 .reduce(0, (a, b) -> a + b);

System.out.println(sum); // output: 15

In this example, we have a list of integers. We use the stream() method to create a stream from the list, then call the reduce() method to combine all the elements of the stream into a single result. The first argument to the reduce() method is the initial value of the result (in this case, 0), and the second argument is a lambda expression that defines how to combine two elements of the stream. In this case, the lambda expression is (a, b) -> a + b, which simply adds two integers together. The output of the program is the sum of all the numbers in the list, which is 15.

Example of using the Java Stream collect() method

List<String> words = Arrays.asList("hello", "world", "java");

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

System.out.println(uppercaseWords); // output: [HELLO, WORLD, JAVA]

In this example, we have a list of strings. We use the stream() method to create a stream from the list, then call the map() method to convert each string to uppercase. We then call the collect() method to gather the resulting strings into a list. The Collectors.toList() method is a factory method that returns a Collector object that can be used to collect the elements of a stream into a list. The output of the program is a list of uppercase strings.

Example of using the Java Stream count() method

List<String> words = Arrays.asList("hello", "world", "java");

long count = words.stream()
                  .count();

System.out.println(count); // output: 3

In this example, we have a list of strings. We use the stream() method to create a stream from the list, then call the count() method to count the number of elements in the stream. The output of the program is the number of elements in the stream, which is 3 in this case.

Example of using the Java Stream anyMatch() method

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

boolean hasEven = numbers.stream()
                         .anyMatch(n -> n % 2 == 0);

if (hasEven) {
    System.out.println("The list contains at least one even number");
} else {
    System.out.println("The list contains only odd numbers");
}

In this example, we have a list of integers. We use the stream() method to create a stream from the list, then call the anyMatch() method to check if any element of the stream is even. The argument to the anyMatch() method is a lambda expression that defines the condition to check. In this case, the lambda expression is n -> n % 2 == 0, which checks if a number is even. The output of the program depends on the contents of the list. If the list contains at least one even number, the program outputs “The list contains at least one even number”. Otherwise, it outputs “The list contains only odd numbers”.

Example of using the Java Stream allMatch() method

List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);

boolean allEven = numbers.stream()
                         .allMatch(n -> n % 2 == 0);

if (allEven) {
    System.out.println("All numbers are even");
} else {
    System.out.println("At least one number is odd");
}

In this example, we have a list of integers. We use the stream() method to create a stream from the list, then call the allMatch() method to check if all elements of the stream are even. The argument to the allMatch() method is a lambda expression that defines the condition to check. In this case, the lambda expression is n -> n % 2 == 0, which checks if a number is even. The output of the program depends on the contents of the list. If all numbers in the list are even, the program outputs “All numbers are even”. Otherwise, it outputs “At least one number is odd”.

Example of using the Java Stream nonMatch() method

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

boolean noneEven = numbers.stream()
                          .noneMatch(n -> n % 2 == 0);

if (noneEven) {
    System.out.println("None of the numbers are even");
} else {
    System.out.println("At least one number is even");
}

In this example, we have a list of integers. We use the stream() method to create a stream from the list, then call the noneMatch() method to check if none of the elements of the stream are even. The argument to the noneMatch() method is a lambda expression that defines the condition to check. In this case, the lambda expression is n -> n % 2 == 0, which checks if a number is even. The output of the program depends on the contents of the list. If none of the numbers in the list are even, the program outputs “None of the numbers are even”. Otherwise, it outputs “At least one number is even”.

Example of using the Java Stream max() method

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

Optional<Integer> max = numbers.stream()
                                .max(Integer::compareTo);

if (max.isPresent()) {
    System.out.println("The maximum element is " + max.get());
} else {
    System.out.println("The stream is empty");
}

In this example, we have a list of integers. We use the stream() method to create a stream from the list, then call the max() method to find the maximum element of the stream. The argument to the max() method is a comparator that is used to compare the elements of the stream. In this case, we use the Integer::compareTo method reference, which compares two integers for order. The output of the program is the maximum element of the stream, if it exists, or a message indicating that the stream is empty.

Leave a Comment

Your email address will not be published. Required fields are marked *

Exit mobile version