Streams API in Java

  • By Shital Chauhan
  • June 22, 2024
  • JAVA Programming
Streams API in Java

Streams API in Java

The Streams API, introduced in Java 8, gives an efficient and fast way to process the collections. This API allows for functional programming-style operations on streams of elements, making data processing concise and readable. In this blog, we’ll delve into the essentials of the Streams API in Java, covering its creation, intermediate and terminal operations, and practical examples to illustrate its power.

 

What is a Stream in Java

A Stream in Java represents a sequence of elements that can be processed in parallel or sequentially. Streams provide abstraction for operations on collections, and filtering and give efficient and clean code. However, it’s important to note that streams only process the data they do not hold the data. It will not change the data it will only process it.

 

How to create the stream

Streams can be created in various ways, such as collections, arrays, or I/O channels. Here are some common ways to create streams:

  • Using Collection:

 

List<String> list1 = Arrays.asList(“a”, “b”, “c”); 

Stream<String> stream = list1.stream();

  • Using Arrays

 

String[] myArray = {“a”, “b”, “c”};

Stream<String> stream = Arrays.stream(myArray);

  • Using Stream.of

 

Stream<String> stream = Stream.of(“a”, “b”, “c”);

The following diagram shows the processing stages of streams API in Java

 

For Free, Demo classes Call: 020-71173125

Registration Link: Java Classes in Pune!

 

 

Intermediate Operations

Intermediate operations return another stream as a result. They are lazily evaluated, meaning they are not executed until a terminal operation is invoked. Common intermediate operations include:

  • filter: Filters elements based on a predicate.

List<String>filter1=list1.stream().

filter(s.startsWith(“a”))

.collect(Collectors.toList());

  • map: Transforms each element using a function.

List<Integer> lengths = list1.stream()

                              .map(String::length)

                              .collect(Collectors.toList());

  • sorted: Sorts elements based on a comparator.

List<String> sorted = list1.stream()

                            .sorted()

                            .collect(Collectors.toList());

  • distinct: Removes duplicate elements.

            List<String> distinct = list1.stream()

                              .distinct()

                              .collect(Collectors.toList());

 

 

Terminal Operations

Terminal operations consume the stream and produce the result based on operations like filter, map, reduce, etc.

Common terminal operations include:

  1. collect: Collect elements into a collection.

List<String> list = list1.stream().collect(Collectors.toList());

  1. forEach: Performs an action for each element.

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

 

  1. reduce: Reduces elements to a single value using an accumulator.

Optional<String> concatenated = list1.stream() .reduce((s1, s2) -> s1 + s2);

 

  1. count: Returns the count of elements.

long count = list1.stream()

                   .count();

  1. findFirst: Returns the first element in the stream.

Optional<String> first = list1.stream().findFirst();

 

 

Example of Streams API

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

import java.util.stream.Stream;

class Employee

{

int id;

String name,department;

double sal;

//constructor

public Employee() {

super();

}

public Employee(int id, String name, String department, double sal) {

super();

this.id = id;

this.name = name;

this.department = department;

this.sal = sal;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getDepartment() {

return department;

}

public void setDepartment(String department) {

this.department = department;

}

public double getSal() {

return sal;

}

public void setSal(double sal) {

this.sal = sal;}

@Override

public String toString() {

return “Employee [id=” + id + “, name=” + name + “, department=” + department + “, sal=” + sal + “]”;

}

}

public class TestStreamsAPI {

 

public static void main(String[] args) {

 

List<Employee> emplist=Arrays.asList(new Employee(101,“Sumit”,“sales”,35000.0),

new Employee(102,“Megha”,“sales”,45000.0),

new Employee(103,“Ram”,“Purchase”,67000.0),

new Employee(104,“Kumar”,“Development”,68000.0),

new Employee(105,“Rohan”,“sales”,50000.0),

new Employee(106,“Suresh”,“sales”,65000.0)

); 

Stream<Employee> stream1=emplist.stream();

//find employee whose salary>60000

System.out.println(“Employees whose salary>60000.0”);

List<Employee> list1=stream1.filter(emp->emp.getSal()>60000.0).collect(Collectors.toList());

list1.forEach(x->System.out.println(x));

System.out.println(“Employee belongs to sales department”);

//Find employees who belongs to sales department

List<Employee>list2=emplist.stream().filter(emp->emp.getDepartment().equals(“sales”)).collect(Collectors.toList());

list2.forEach(x->System.out.println(x));

//print the names of all employees

System.out.println(“Names of all employees are”);

List<String> list3=emplist.stream().map(emp->emp.getName()).collect(Collectors.toList());

list3.forEach(System.out::println);

//count the number of employees

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

System.out.println(“Number of employees are “+count);

}

 

 

Conclusion

The Streams API in Java is a transformative tool for processing collections of data in a declarative and clean way. By utilizing intermediate and terminal operations, we can write concise and efficient code. Whether we are filtering, transforming, or aggregating data, prepare for your next tech interview with our comprehensive guide to Core Java Interview Questions and Answers for 2024. Get ready to ace your Java interview!

 

Note: Do watch our latest video: Click Here

 

Author:-

Shital Chauhan
Call the Trainer and Book your free demo class for Java now!!!

© Copyright 2020 | SevenMentor Pvt Ltd.

Submit Comment

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

*
*