Short circuit operations in Java 8

In we post we will discuss Java 8 stream short-circuit. As we know java stream has only two types of operation one is java stream terminal operations and another is java stream intermediate operations. The short circuit operations are part of the intermediate operation and terminal operation. In this topic, we will some the operation findFirst() method, limit() method, findAny(), anyMatch(), allMatch(), noneMatch().

Here is the table content of the article will we will cover this topic.
1. What are the Short circuit operations in Java 8?
2. Stream<T> limit(long maxSize)
3. Optional<T> findFirst()
4. Optional<T> findAny()
5. boolean anyMatch()
6. boolean allMatch()
7. boolean noneMatch()

What is the Java 8 stream short-circuit?

Short-circuit operations are just like boolean short-circuiting in java.
Let’s take an example of boolean short-circuiting.

if(a > 0 & b >0)

The second condition is evaluated only if the first condition does (a > 0) is true otherwise it skips the second condition (b > 0). Java 8 also supports the short-circuiting in Stream.

There is some operation which is short-circuiting.

Stream short-circuit operations

Stream<T> limit(long maxSize)

The limit method declared in the Stream interface. It accepts a parameter of a long type.  
maxsize: It the maximum size of elements in Stream. A Stream can’t hold the elements greater than maxSize.
Returns a new stream created from this stream.

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

public class ExampleOfLimit
{
	public static void main(String[] args) 
	{
		List<String> names = new ArrayList<String>();
		names.add("RAM");
		names.add("Ravi");
		names.add("Sham");
		names.add("Shiv");
		names.add("Raman");
		
		// Set up the limit of elements in Stream
		names.stream().limit(3).forEach((student) -> System.out.println("Name of Student:"+ student));
	}

}

Output: Name of Student:RAM
Name of Student:Ravi
Name of Student:Sham

import java.util.ArrayList;

public class ExampleOfLimitInUserDefined 
{
	public static void main(String[] args) 
	{
		ArrayList<Book> listOfBook = new ArrayList<Book>();
		listOfBook.add(new Book(1011, "Digital", "RRK"));
		listOfBook.add(new Book(1012, "Mathemetics", "LP"));
		listOfBook.add(new Book(1033, "LOC", "PO"));
		listOfBook.add(new Book(1048, "PC", "SK"));
		listOfBook.add(new Book(1050, "Fundamental", "NMM"));
		
		// Set up the limit of elements in Stream
		listOfBook.stream().limit(2).forEach((book) ->
		{
			System.out.println("Id of Book:"+ book.getBookId());
			System.out.println("Name of Book:"+ book.getName());
			System.out.println("Author of Book:"+ book.getAuthorName());
		});	
	}
}


class Book 
{
	int bookId;
	String name;
	String authorName;
	public Book(int bookId, String name, String authorName) 
	{
		this.bookId = bookId;
		this.name = name;
		this.authorName = authorName;
	}
	public int getBookId() 
	{
		return bookId;
	}
	public void setBookId(int bookId) 
	{
		this.bookId = bookId;
	}
	public String getName() 
	{
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthorName() {
		return authorName;
	}
	public void setAuthorName(String authorName) {
		this.authorName = authorName;
	}
}

Output: Id of Book:1011
Name of Book:Digital
Author of Book:RRK
Id of Book:1012
Name of Book:Mathemetics
Author of Book:LP

Optional<T> findFirst()

The findFirst method is declared in the Stream interface. This method returns the first element from Stream or returns empty(Optional object) if Stream is empty. It is the terminal operation of Stream because you can use the stream after the usage of findFirst.
return: It returns an object of Optional type.
throws NullPointerException if the element selected is null.

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

public class ExampleOfFindFirst
{
	public static void main(String[] args) 
	{
		List<Integer> listOfNumber = Arrays.asList(10, 5, 6, 11, 8);
		
		List<String> names = new ArrayList<String>();
		names.add("RAM");
		names.add("Ravi");
		names.add("Sham");
		names.add("Shiv");
		names.add("Raman");
		
		// Finding the first element from Stream
		Optional<Integer> number = listOfNumber.stream().findFirst();
		if(number.isPresent())
			System.out.println("First element from Stream : "+ number.get());
		else
			System.out.println("Stream is empty");
		
		// Find first name start with R
		Optional<String> nameFrom = names.stream().filter(s -> s.startsWith("R")).findFirst();
		if(nameFrom.isPresent())
			System.out.println("Name start from R:"+nameFrom.get());
		else
			System.out.println("There is not name start from R:"+nameFrom.get());
	}

}

Output: First element from Stream : 10
Name start from R:RAM

import java.util.ArrayList;
import java.util.Optional;

public class ExampleOfFindFirstInUserDefined 
{
	public static void main(String[] args) 
	{
		ArrayList<Student> listOfStudent = new ArrayList<Student>();
		listOfStudent.add(new Student(010, "MTech", "Ram"));
		listOfStudent.add(new Student(200, "MCA", "Sham"));
		listOfStudent.add(new Student(103, "MCA", "Mohan"));
		listOfStudent.add(new Student(148, "BCA", "Lia"));
		listOfStudent.add(new Student(050, "BCOM", "Rai"));
		
		//Fining first the first student in Stream
		Optional<Student> firstStudent = listOfStudent.stream().findFirst();
		if(firstStudent.isPresent())
			System.out.println("Name of first Student: "+ firstStudent.get().getName());
		
		// Finding first student from class MCA
		Optional<Student> firstStudentFromMCA = listOfStudent.stream()
				.filter(student -> student.getClassName().equals("MCA")).findFirst();
		if(firstStudentFromMCA.isPresent())
		System.out.println("Name of first Student from MCA: "+ firstStudentFromMCA.get().getName());
		
	}
}

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;
	}
}

Output: Name of first Student: Ram
Name of first Student from MCA: Sham

Optional<T> findAny()

The findAny() method is declared in the Stream interface. This method returns any element from Stream or returns empty(Optional object) if Stream is empty. It is the terminal operation of Stream because you can use the stream after the usage of findFirst.
return: It returns an object of Optional type.
throws NullPointerException if the element selected is null.

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

public class ExampleOfFindFirst
{
	public static void main(String[] args) 
	{
		List<Integer> listOfNumber = Arrays.asList(10, 5, 6, 11, 8);
		
		List<String> names = new ArrayList<String>();
		names.add("RAM");
		names.add("Ravi");
		names.add("Sham");
		names.add("Shiv");
		names.add("Raman");
		
		// Finding the any element from Stream
		Optional<Integer> number = listOfNumber.stream().findAny();
		if(number.isPresent())
			System.out.println("Any element from Stream : "+ number.get());
		else
			System.out.println("Stream is empty");
		
		// Find Any name start with S
		Optional<String> nameFrom = names.stream().filter(s -> s.startsWith("S")).findAny();
		if(nameFrom.isPresent())
			System.out.println("Name start from S:"+nameFrom.get());
		else
			System.out.println("There is not name start from S");
	}

}

Output: Any element from Stream : 10
Name start from S:Sham

import java.util.ArrayList;
import java.util.Optional;

public class ExampleOfFindFirstInUserDefined 
{
	public static void main(String[] args) 
	{
		ArrayList<Student> listOfStudent = new ArrayList<Student>();
		listOfStudent.add(new Student(010, "MTech", "Ram"));
		listOfStudent.add(new Student(200, "MCA", "Sham"));
		listOfStudent.add(new Student(103, "MCA", "Mohan"));
		listOfStudent.add(new Student(148, "BCA", "Lia"));
		listOfStudent.add(new Student(050, "BCOM", "Rai"));
		
		//Fining any student in Stream
		Optional<Student> anyStudent = listOfStudent.stream().findAny();
		if(anyStudent.isPresent())
			System.out.println("Name of Any Student: "+ anyStudent.get().getName());
		
		// Finding any student from class MCA
		Optional<Student> anyStudentFromMCA = listOfStudent.stream()
				.filter(student -> student.getClassName().equals("MCA")).findAny();
		if(anyStudentFromMCA.isPresent())
		System.out.println("Name of any Student from MCA: "+ anyStudentFromMCA.get().getName());
		
	}
}

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;
	}
}

Output: Name of Any Student: Ram
Name of any Student from MCA: Sham

boolean 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

boolean 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 all 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("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

boolean 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 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

Leave a Comment