Terminal operations in java 8

Here is the table content of the article will we will cover this topic.
1. What are the terminal operations in Java 8?
2. forEach()
3. Collect()
4. reduce()
5. match()
6. count()

What are the terminal operations in Java 8?

The terminal operation doesn’t return any stream. It returns a result of a certain type.

1. The terminal operations take Stream as input and produce the result.
2. After completion of the Terminal operation, you can’t use the Stream.
3. Terminal operation is eager in nature. The terminal operation processes all the elements of the stream before returning the result.

Let’s discuss some Terminal operations:
1. forEach()
2. Collect()

3. reduce()
4. match()
5. count()

1. forEach()

The forEach() method is declared in Stream Interface. The Stream interface is just declaring the forEach() method. The implements will be provided during the use of Streams.

void forEach(Consumer<? super T> action);

The forEach() method works as a utility method that helps to iterate over a collection or stream. The forEach() method accepts the reference of Consumer Interface and performs a certain action on each element of it which define in Consumer.
As you can see forEach() accepts reference of Consumer that is action. The action will be provided by a class that implements the Consumer interface and is passed to forEach as an argument.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExampleOfForEach
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Ram");
		names.add("Sham");
		names.add("Krishna");
		
		// Printing names from list of String 
		System.out.println("Names from List:");
		names.stream().forEach(System.out::println);
		
		
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
		
		// Printing numbers from list of number 
		System.out.println("Numbers from List:");
		numbers.stream().forEach(System.out::println);		
		
	}
}

Output: Book Id = 212
Book Name = Digital
Book Author = PK
Book Id = 819
Book Name = Mathematics
Book Author = OL
Book Id = 201
Book Name = ROM
Book Author = SM
Book Id = 862
Book Name = LOC
Book Author = DM

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExampleOfForEach
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Ram");
		names.add("Sham");
		names.add("Krishna");
		
		// Printing names from list of String 
		System.out.println("Names from List:");
		names.stream().forEach(System.out::println);
		
		
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
		
		// Printing numbers from list of number 
		System.out.println("Numbers from List:");
		numbers.stream().forEach(System.out::println);
	}

}

Output: Names from List:
Ram
Sham
Krishna
Numbers from List:
1
2
3
4

2. Collect()

This method is declared in the Stream interface. It accepts Collectors as a  parameter. The collect() method is used to get all the elements from a stream and store them in the Collection. This method works based on the equals method of the class. It is a terminal operation because it produces the result from Stream.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class ExampleOfCollect
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Ram");
		names.add("Sham");
		names.add("Krishna");
		
		
		List<String> filteredStringList = names.stream().filter((a) -> a.length() >3).collect(Collectors.toList());
		// Printing names from list of String 
		System.out.println("Names from Filtered List:");
		filteredStringList.forEach(System.out::println);
		
		List<Integer> numbers = Arrays.asList(1, 3, 98, 24);
		List<Integer> filteredNumberList = numbers.stream().filter((a) -> a > 2).collect(Collectors.toList());
		// Printing numbers from list of number 
		System.out.println("Numbers from Filtered List:");
		filteredNumberList.stream().forEach(System.out::println);		
	}
}

Output: Names from Filtered List:
Sham
Krishna
Numbers from Filtered List:
3
98
24

import java.util.ArrayList;
import java.util.stream.Collectors;

public class ExampleOfCollectInUserDefined 
{
	public static void main(String[] args) 
	{
		ArrayList<Student> listOfStudent = new ArrayList<Student>();
		listOfStudent.add(new Student(101, "MCA", "Ram"));
		listOfStudent.add(new Student(102, "MCA", "Sham"));
		listOfStudent.add(new Student(103, "MCA", "Krishna"));
		listOfStudent.add(new Student(104, "MCA", "Satyam"));
		listOfStudent.add(new Student(105, "MCA", "Joshi"));
		
		ArrayList<Student> filteredList = (ArrayList<Student>) listOfStudent.stream()
			.filter((student) -> student.getRollNo() > 103)
			.collect(Collectors.toList());
		
		filteredList.stream().forEach((student) ->
		{
			System.out.println("RollNo = "+ student.getRollNo());
			System.out.println("Name = "+ student.getName());
			System.out.println("Class Name = "+ student.getClassName());
			
		});
	}
	
	
}


class Student 
{
	int rollNo;
	String className;
	String name;
	
	public Student(int rollNo, String className, String name) 
	{
		this.rollNo = rollNo;
		this.className = className;
		this.name = name;
	}
	public int getRollNo() 
	{
		return rollNo;
	}
	public void setRollNo(int rollNo) 
	{
		this.rollNo = rollNo;
	}
	public String getClassName() 
	{
		return className;
	}
	public void setClassName(String className) 
	{
		this.className = className;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public boolean equals(Object obj) 
	{
		return this.rollNo == ((Student)obj).getRollNo();
	}
	@Override
	public int hashCode() 
	{
		return this.rollNo;
	}
}

Output: RollNo = 104
Name = Satyam
Class Name = MCA
RollNo = 105
Name = Joshi
Class Name = MCA

3. reduce()

This method is declared in the Stream interface. It accepts an object of BinaryOperator. This method is used to reduce the element of Stream.  It returns the object of Optional.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class ExampleOfReduce
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Hi");
		names.add("This");
		names.add("is");
		names.add("learning");
		names.add("Website");
		names.add("of");
		names.add("Java");
		
		System.out.println("Concatinating all String of list by reduce:");
		Optional<String> objOptional = names.stream().reduce((string1, string2) -> string1.concat(" "+string2));
		String mainString = objOptional.get();
		System.out.println("Concatinated String = "+mainString);
		
		
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
		
		System.out.println("Add all numbers of list by reduce:");
		Optional<Integer> objOptional2 = numbers.stream().reduce((a, sum) -> sum+a);
		int sumOfAll = objOptional2.get();
		System.out.println("Sum of all number ="+sumOfAll);
		
	}
}

4. match()

You can check whether the element is matched in Stream or not. The stream has various operations that are used to check whether a certain predicate matches the stream.

anyMatch(): This method is declared in the Stream interface. It accepts a predicate as a parameter. The predicate checks each element of the stream. If any element satisfies the condition of predicate it returns true otherwise false.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class ExampleOfReduce
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Java");
		names.add("Goal");
		names.add("Website");
		names.add("JavaGoal.com");
		
		boolean isMatchedString = names.stream().anyMatch((a) -> a.startsWith("Java"));
		System.out.println("Is string found = "+isMatchedString);
		
		boolean isMatchedString2 = names.stream().anyMatch((a) -> a.startsWith("Java"));
		System.out.println("Is string found = "+isMatchedString2);
		
		
		List<Integer> numbers = Arrays.asList(13, 82, 43, 41);
		
		boolean isMatchednumbers = numbers.stream().anyMatch((a) -> (a > 20));
		System.out.println("Is any number found = "+isMatchednumbers);
		
		boolean isMatchednumbers2 = numbers.stream().anyMatch((a) -> (a < 10));
		System.out.println("Is any number found = "+isMatchednumbers2);
		
	}

}

Output: Is string found = true
Is string found = true
Is any number found = true
Is any number found = false

allMatch(): This method is declared in the Stream interface. It accepts a predicate as a parameter. The predicate checks each element of the stream. If any element satisfies the condition of the predicate it returns true otherwise false.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class ExampleOfReduce
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Java");
		names.add("Java Goal");
		names.add("Java Website");
		names.add("JavaGoal.com");
		
		boolean isAllStringMatched = names.stream().allMatch((a) -> a.startsWith("Java"));
		System.out.println("Is All string Start with Java = "+isAllStringMatched);
		
		boolean isAllStringMatched2 = names.stream().allMatch((a) -> a.startsWith("JavaGoal"));
		System.out.println("Is All string Start with JavaGoal = "+isAllStringMatched2);
		
		List<Integer> numbers = Arrays.asList(13, 82, 43, 41);
		
		boolean isAllnumbersMatched = numbers.stream().anyMatch((a) -> (a > 5));
		System.out.println("Is all number greater than 5 = "+isAllnumbersMatched);
		
		boolean isMatchednumbers2 = numbers.stream().anyMatch((a) -> (a < 25));
		System.out.println("Is all number less than 25 = "+isMatchednumbers2);
		
		
	}
}

Output: Is All string Start with Java = true
Is All string Start with JavaGoal = false
Is all number greater than 5 = true
Is all number less than 25 = true

noneMatch(): This method is declared in the Stream interface. It accepts a predicate as a parameter. The predicate checks each element of the stream. If there is no element that satisfies the condition of the predicate it returns true otherwise false.

package StreamIntermediate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class ExampleOfReduce
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Java");
		names.add("Java Goal");
		names.add("Java Website");
		names.add("JavaGoal.com");
		
		boolean isNoneStringMatched = names.stream().noneMatch((a) -> a.startsWith("Web"));
		System.out.println("None of the string Start with Web = "+isNoneStringMatched);
		
		boolean isNoneStringMatched2 = names.stream().noneMatch((a) -> a.startsWith("Java"));
		System.out.println("None of the string Start with Java = "+isNoneStringMatched2);
		
		List<Integer> numbers = Arrays.asList(13, 82, 43, 41);
		
		boolean isNoneMatched = numbers.stream().noneMatch((a) -> (a < 10));
		System.out.println("None of the number less than 5 = "+isNoneMatched);
		
		boolean isNoneMatched2 = numbers.stream().noneMatch((a) -> (a > 25));
		System.out.println("None of the number greater than 25 = "+isNoneMatched2);
			
	}

}

Output: None of the string Start with Web = true
None of the string Start with Java = false
None of the number less than 5 = true
None of the number greater than 25 = false

5. count()

This method is declared in the Stream interface. It doesn’t accept any parameters. It returns the count of the element that is present in the stream. If there is no element in the stream it returns 0. It returns the value in a long datatype.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExampleOfReduce
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("Hi");
		names.add("Hello");
		names.add("Java Website");
		names.add("JavaGoal.com");
		
		long count = names.stream().count();
		System.out.println("Count of element of Stream is = "+count);
		
		
		List<Integer> numbers = new ArrayList<Integer>();
		
		long count1 = numbers.stream().count();
		System.out.println("Count of element of Stream is = "+count1);
		
			
	}

}

Output: Count of element of Stream is = 4
Count of element of Stream is = 0

import java.util.ArrayList;
import java.util.stream.Collectors;

public class ExampleOfCollectInUserDefined 
{
	public static void main(String[] args) 
	{
		ArrayList<Student> listOfStudent = new ArrayList<Student>();
		listOfStudent.add(new Student(101, "MCA", "Ram"));
		listOfStudent.add(new Student(102, "MCA", "Sham"));
		listOfStudent.add(new Student(103, "MCA", "Krishna"));
		listOfStudent.add(new Student(104, "MCA", "Satyam"));
		listOfStudent.add(new Student(105, "MCA", "Joshi"));
		
		long countOfStudent = listOfStudent.stream().filter((student) -> student.getClassName().equals("MCA"))
			.count();
		System.out.println("Number of student in MCA class = "+ countOfStudent);
		
	}
	
	
}


class Student 
{
	int rollNo;
	String className;
	String name;
	
	public Student(int rollNo, String className, String name) 
	{
		this.rollNo = rollNo;
		this.className = className;
		this.name = name;
	}
	public int getRollNo() 
	{
		return rollNo;
	}
	public void setRollNo(int rollNo) 
	{
		this.rollNo = rollNo;
	}
	public String getClassName() 
	{
		return className;
	}
	public void setClassName(String className) 
	{
		this.className = className;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public boolean equals(Object obj) 
	{
		return this.rollNo == ((Student)obj).getRollNo();
	}
	@Override
	public int hashCode() 
	{
		return this.rollNo;
	}
}

Output: Number of student in MCA class = 5

Leave a Comment