Java Optional example

In Java 8 with the introduction of Lambda and the Optional class, we can filter a Stream and if any Object is returned, we can call a method with that Object.

Syntax:

	ifPresent( a -> {  } );

Using the ifPresent method allows to write cleaner code as we don't have to test if the Object returned is null or not.

Example:

Here is an example creating a Stream of String. First, it tries to find the first element using an Optional Object. Then a Stream is filtered using a value that doesn't exist and the code gets an Optional for the first value that doesn't exists. The boolean isPresent is false. Final, the code creates a Stream, filters on a value that exists, finds the first value and ifPresent write the value with a message in the output.

Create the following java file:

import java.util.Optional;
import java.util.stream.Stream;

public class LambdaOptional {

	public static void main(String[] argv){
		// Create the Stream
		Stream<String> stream = Stream.of( "a", "c", "a", "b", "b");
		
		// Get the first element from the Stream
		Optional<String> op = stream.findFirst();
		
		System.out.println( "isPresent: " + op.isPresent()  );
		System.out.println( "first element: " + op.get() );

		// Same test with a value that doesn't exist
		op = Stream.of( "a", "c", "a", "b", "b")
				.filter( a -> a.equals( "z" ) )
				.findFirst();

		System.out.println( "isPresent: " + op.isPresent()  );
		
		// Same test using ifPresent
		Stream.of( "a", "c", "a", "b", "b")
				.filter( a -> a.equals( "a" ) )
				.findFirst()
				.ifPresent( a -> System.out.println( "Value found: " + a ) );
	}
}

The output will be:

isPresent: true
first element: a
isPresent: false
Value found: a

References:

Lambda Expressions

Recent Comments