Java Stream API Example

 Do you need a java feature which process a sequence of elements? If your answer is yes…. Java stream API is used.

A collection of data is involved for performing functional-style operations.

Features:

Some of the features in the Java Stream API are listed below…

Stream: It has a pipeline which process the sequential elements. It processes from source to destination.

Intermediate operations: when you want to transform a stream into another stream, some of the functions are used.

Eg: distinct(),filter(),limit(),map(),sorted(),skip()

Terminal operations: when these operations executed, some results are produced.

Eg: anyMatch(),allMatch(),collect(),count(), forEach(),reduce().

Let us implement a java program to illustrate java Stream API.

Program implementation:

  • ·       First,include the builtin packages.
  • ·       Create a class with main() function.
  • ·       A list c_names is created with array elements.
  • ·       Convert into uppercase and store the c_names into a list.
  • ·       Print the name which starts with ‘J’.
  • ·       For performing the parallel processing, create a integer array and find the sum of integer values.

Program:

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

public class StreamEg4 {

    public static void main(String[] args) {

        List<String> c_names = Arrays.asList("Ajay", "Bobby", "Chandru", "Das", "John","James","Hari","Ravi","Vibhav");

       // convert the names into Uppercase and store into a list

        List<String> uCaseNames = c_names.stream()

                                            .map(String::toUpperCase)

                                            .collect(Collectors.toList());

         System.out.println(uCaseNames);

        System.out.println("List the name starts with 'J'");

        // Filter names that start with 'J' and print them

        c_names.stream()

             .filter(name -> name.startsWith("J"))

             .forEach(System.out::println);

        //Print sum of 5 numbers for Parallel streaming

       System.out.println("The sum of 5 numbers by Parallel streaming");

       List<Integer> nos = Arrays.asList(11, 12, 31, 45, 75);

       int sum = nos.parallelStream()

                    .reduce(0, Integer::sum);

       System.out.println("The Sum is: " + sum);

         }

}

Here, is the output.

C:\raji\blog>javac StreamEg4.java

C:\raji\blog>java StreamEg4

[AJAY, BOBBY, CHANDRU, DAS, JOHN, JAMES, HARI, RAVI, VIBHAV]

List the name starts with 'J'

John

James

The sum of 5 numbers by Parallel streaming

The Sum is: 174

That’s the program to illustrate the java Stream API  is executed successfully. Keep coding!!!

No comments:

Post a Comment