Intermediate & Terminal Operations in Java 8

Java Fusion
3 min readApr 9, 2024

--

Bhairab Patra (java Fusion)

Stream API’s operations are broadly categorized into two types based on their behavior.

Intermediate operations & Terminal operations.

Intermediate Operations

  • These operations transform the elements of a stream and return a new stream as a result.
  • Intermediate operations do not produce a final result directly. they are usually combined using method chaining.
  • Examples of some common intermediate operations are filter, map, sorted, distinct, limit, flatMap, skip, etc.

Terminal Operations

  • Terminal operations produce a result such as a value or a collection.
  • Examples of some common terminal operations are collect, forEach, reduce, count, anyMatch, allMatch, noneMatch, etc.

Here’s an example of using intermediate operations


import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class IntermediateOperations {

public static void main(String[] args) {

List<Employee> employees = Arrays.asList(
new Employee("Muna", "IT", 7500),
new Employee("Runa", "HR", 90000),
new Employee("Kuna", "Finance", 60000),
new Employee("Miku", "IT", 75000),
new Employee("Sonu", "IT", 24000),
new Employee("mark", "HR", 65000)
);

// Filter words that start with "M"
List<Employee> emp = employees.stream()
.filter(employee -> employee.getName().startsWith("M"))
.toList();
System.out.println("Filtered words: " + emp); // approach 1 to display emp whose name start with "M"
emp.forEach(employee -> System.out.println(employee.getName())); // approach 2 to display emp whose name start with "M"
emp.forEach(System.out::println); // // approach 3 to display emp whose name start with "M"

// Map words to uppercase

List<String> uppercaseWords = employees.stream().map(employee -> employee.getName()
.toUpperCase())
.toList();
System.out.println(uppercaseWords); // [MUNA, RUNA, KUNA, MIKU, SONU, MARK]

List<String> sortedEmployeeName = employees.stream()
.sorted(Comparator.comparing(employee -> employee.getName()))
.map(employee -> employee.getName())
.collect(Collectors.toList());

System.out.println(sortedEmployeeName); // [Kuna, Miku, Muna, Runa, Sonu, mark]


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

List<String> distinctEords = words.stream().distinct().toList();
System.out.println("distinct words" + distinctEords);

List<String> sorted = words.stream().sorted(Comparator.reverseOrder()).toList();
System.out.println(sorted); //[world, world, stream, java, hello, hello, example]

List<String> skipItem = words.stream().skip(2).toList();
System.out.println(skipItem); //[world, world, java, stream, example]

List<String> limitItem = words.stream().distinct().limit(3).toList();
System.out.println(limitItem); //[hello, world, java]

}
}

In this example

  • filter is used to filter employee names starting with “M”.
  • map is used to transform the employee name to uppercase.
  • sorted is used to sort employee names in descending order.
  • distinct is used to get a distinct employee name from the list.
  • Skip is used to skip words from the list.
  • limit is used to limit the words from the list.

Each of these intermediate operations creates a new stream, which allows for further processing or collecting the results into a collection using collect(Collectors.toList()).

Here’s an example of using Terminal operations

package com.shorts.java8.optionalclass.interfacejava8;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class TerminalOperations {

public static void main(String[] args) {

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

// Example 1: Collecting elements into a List and set

List<Integer> integers = numbers.stream()
.map(num -> num * 10)
.collect(Collectors.toList());
System.out.println(integers);

Set<Integer> intMaps = numbers.stream()
.map(num -> num * 10)
.collect(Collectors.toSet());
System.out.println(intMaps);

// Example 2: Counting elements in the stream

long numberCount = numbers.stream().distinct().count();
System.out.println(numberCount);

// Example 3: Checking if any element is greater than 3 anyMatch

boolean anyGreaterThan2 = numbers.stream().anyMatch(num -> num > 2);
System.out.println("Any number greater than 2? " + anyGreaterThan2);

boolean noneMatch = numbers.stream().noneMatch(num -> num > 20);
System.out.println(noneMatch);

boolean allMatch = numbers.stream().allMatch(num -> num > 0);
System.out.println(allMatch);

// Example 4: Reducing elements to find the sum

int sum = numbers.stream().reduce(0, Integer::sum);
System.out.println(sum);
}
}

In this example

  • collect terminal operation to collect doubled numbers into a List.
  • count terminal operation counts the number of elements in the stream.
  • anyMatch terminal operation checks if any element in the stream is greater than 2.
  • reduce terminal operation calculates the sum of elements in the stream.

Each terminal operation performs a specific action on the stream and returns a result or a boolean value based on the operation.

Thank You !!!

--

--

Java Fusion

Java enthusiast crafting code with passion. enthusiastic about creating robust, scalable applications. Let's code, innovate, and build the future together!