Java Optional Archives - Huong Dan Java https://huongdanjava.com/tag/java-optional-en Java development tutorials Mon, 04 Jan 2021 23:23:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://huongdanjava.com/wp-content/uploads/2018/01/favicon.png Java Optional Archives - Huong Dan Java https://huongdanjava.com/tag/java-optional-en 32 32 flatMap() method of Optional object in Java https://huongdanjava.com/flatmap-method-of-optional-object-in-java.html https://huongdanjava.com/flatmap-method-of-optional-object-in-java.html#respond Sat, 17 Feb 2018 08:58:59 +0000 https://huongdanjava.com/?p=6696 As you all know, the Optional object is a generic object, its data type can be any object, and therefore, we can meet the case that its data type is also an Optional object, such as: Optional<Optional<String>>. To resolve this problem, Java introduces us to… Read More

The post flatMap() method of Optional object in Java appeared first on Huong Dan Java.

]]>
As you all know, the Optional object is a generic object, its data type can be any object, and therefore, we can meet the case that its data type is also an Optional object, such as: Optional<Optional<String>>. To resolve this problem, Java introduces us to the flatMap() method so that Optional’s data type is simpler: Optional<String> for example.

For example, I have the following method:

public String findName() {
    // Do something
    return null;
}

To avoid the Null Pointer Exception, I will rewrite the above method with Optional object:

public Optional<String> findName() {
    // Do something
    return Optional.empty();
}

Now, if you use the above method with the map() method in the Optional object:

package com.huongdanjava.javaexample;

import java.util.Optional;

public class Example {

	public Optional<String> findName() {
	    // Do something
	    return Optional.empty();
	}

	public static void main(String[] args) {
		Example e = new Example();
		Optional<Example> opt = Optional.ofNullable(e);
		System.out.println(opt.map(x -> x.findName()));
	}

}

The return value of the map() method will be:

flatMap() method of Optional object in Java

As you can see, here the return result is an Optional object of the Optional object.

If we now use the flatMap() method instead of the map() method:

package com.huongdanjava.javaexample;

import java.util.Optional;

public class Example {

	public Optional<String> findName() {
	    // Do something
	    return Optional.empty();
	}

	public static void main(String[] args) {
		Example e = new Example();
		Optional<Example> opt = Optional.ofNullable(e);
		System.out.println(opt.flatMap(x -> x.findName()));
	}

}

then the return value type will be much simpler:

flatMap() method of Optional object in Java

 

The post flatMap() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/flatmap-method-of-optional-object-in-java.html/feed 0
isPresent() method of Optional object in Java https://huongdanjava.com/ispresent-method-optional-object-java.html https://huongdanjava.com/ispresent-method-optional-object-java.html#respond Mon, 12 Feb 2018 22:53:14 +0000 https://huongdanjava.com/?p=6685 This method will check whether an Optional object is not empty? If this object is empty, it returns false. For example: [crayon-69bb46802a366275547085/] Result:

The post isPresent() method of Optional object in Java appeared first on Huong Dan Java.

]]>
This method will check whether an Optional object is not empty? If this object is empty, it returns false.

For example:

package com.huongdanjava.javaexample;

import java.util.Optional;

public class Example {

	public static void main(String[] args) {
		String s = new String("Khanh");

		Optional<String> opt = Optional.ofNullable(s);
		System.out.println(opt.isPresent());
	}

}

Result:

isPresent() method of Optional object in Java

The post isPresent() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/ispresent-method-optional-object-java.html/feed 0
map() method of Optional object in Java https://huongdanjava.com/map-method-optional-object-java.html https://huongdanjava.com/map-method-optional-object-java.html#respond Mon, 12 Feb 2018 22:46:09 +0000 https://huongdanjava.com/?p=6679 This method first will check whether our Optional object is empty or not? If not empty, convert its value to another value. Similar to the filter() method, this method returns an Optional object with a value after conversion. For example: [crayon-69bb46802a48a220913303/] In the above example,… Read More

The post map() method of Optional object in Java appeared first on Huong Dan Java.

]]>
This method first will check whether our Optional object is empty or not? If not empty, convert its value to another value. Similar to the filter() method, this method returns an Optional object with a value after conversion.

For example:

package com.huongdanjava.javaexample;

import java.util.Optional;

public class Example {

	public static void main(String[] args) {
		String s = new String("Khanh");

		Optional<String> opt = Optional.ofNullable(s);
		opt.map(x -> x.toLowerCase())
			.filter(x -> x.contains("k"))
			.ifPresent(x -> System.out.println("Name: " + x));
	}

}

In the above example, we used the map() method to convert the value of the Optional object to lowercase, then check whether its value contains the letter “k”. If so, print out that value.

You can see more about the filter() method and ifPresent() method of the Optional object to understand more about the example.

Result:

map() method of Optional object in Java

 

The post map() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/map-method-optional-object-java.html/feed 0
filter() method of Optional object in Java https://huongdanjava.com/filter-method-optional-object-java.html https://huongdanjava.com/filter-method-optional-object-java.html#respond Mon, 12 Feb 2018 22:20:34 +0000 https://huongdanjava.com/?p=6671 This method first will check whether our Optional object is empty or not? If not, then continue to check whether its value meets a certain condition or not? If satisfied, it returns an Optional object containing this value, otherwise returns an empty Optional object. For… Read More

The post filter() method of Optional object in Java appeared first on Huong Dan Java.

]]>
This method first will check whether our Optional object is empty or not? If not, then continue to check whether its value meets a certain condition or not? If satisfied, it returns an Optional object containing this value, otherwise returns an empty Optional object.

For example:

package com.huongdanjava.javaexample;

import java.util.Optional;

public class Example {

	public static void main(String[] args) {
		String s = new String("Khanh");

		Optional<String> opt = Optional.ofNullable(s);
		opt.filter(x -> x.contains("K"))
			.ifPresent(x -> System.out.println("Name: " + x));
	}

}

In the above example, we used the Optional object’s filter() method to check if the string s contained the character “K”. If it contains, prints the whole string.

See more information about ifPresent() method of Optional object at here.

Result:

filter() method of Optional object in Java

 

The post filter() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/filter-method-optional-object-java.html/feed 0
ifPresentOrElse() method of Optional object in Java https://huongdanjava.com/ifpresentorelse-method-optional-object-java.html https://huongdanjava.com/ifpresentorelse-method-optional-object-java.html#respond Mon, 12 Feb 2018 21:57:13 +0000 https://huongdanjava.com/?p=6665 This method was introduced from Java 9. This method is similar to the ifPresent() method which I introduced in this tutorial, but here is a difference since we have one more Runnable parameter, so that in-case if the Optional object is empty, the object of the… Read More

The post ifPresentOrElse() method of Optional object in Java appeared first on Huong Dan Java.

]]>
This method was introduced from Java 9.

This method is similar to the ifPresent() method which I introduced in this tutorial, but here is a difference since we have one more Runnable parameter, so that in-case if the Optional object is empty, the object of the Runnable interface will be executed.

For example:

package com.huongdanjava.javaexample;

import java.util.Optional;

public class Example {

	public static void main(String[] args) {
		String s = null;

		Optional<String> opt = Optional.ofNullable(s);
		opt.ifPresentOrElse(
			x -> System.out.println(x),
			() -> System.out.println("No value"));
	}

}

Result:

ifPresentOrElse() method of Optional object in Java

 

The post ifPresentOrElse() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/ifpresentorelse-method-optional-object-java.html/feed 0
ifPresent() method of Optional object in Java https://huongdanjava.com/ifpresent-method-optional-object-java.html https://huongdanjava.com/ifpresent-method-optional-object-java.html#respond Mon, 12 Feb 2018 07:57:28 +0000 https://huongdanjava.com/?p=6658 This method is used to check whether an Optional object is empty or not? If not, then do the operations with this object, otherwise do not do anything. The parameter of this method is an object of the Consumer interface. You can see more about… Read More

The post ifPresent() method of Optional object in Java appeared first on Huong Dan Java.

]]>
This method is used to check whether an Optional object is empty or not? If not, then do the operations with this object, otherwise do not do anything.

The parameter of this method is an object of the Consumer interface. You can see more about the Consumer interface here.

For example:

package com.huongdanjava.javaexample;

import java.util.Optional;

public class Example {

	public static void main(String[] args) {
		String s = new String("Khanh");

		Optional<String> opt = Optional.ofNullable(s);
		opt.ifPresent(x -> System.out.println(x));
	}

}

Result:

ifPresent() method of Optional object in Java

The post ifPresent() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/ifpresent-method-optional-object-java.html/feed 0
Or() methods of Optional object in Java https://huongdanjava.com/or-methods-optional-object-java.html https://huongdanjava.com/or-methods-optional-object-java.html#respond Thu, 08 Feb 2018 08:07:47 +0000 https://huongdanjava.com/?p=6624 The Optional object in Java has three methods with name start with or(). In this tutorial, we will together learn about them and what is the difference between them. First, I might mention the orElse() method. This method is used to return a default value in… Read More

The post Or() methods of Optional object in Java appeared first on Huong Dan Java.

]]>
The Optional object in Java has three methods with name start with or(). In this tutorial, we will together learn about them and what is the difference between them.

First, I might mention the orElse() method.

This method is used to return a default value in case our Optional object is empty.

The parameter of this method is the default value that will be returned.

For example:

package com.huongdanjava.javaexample;

import java.io.IOException;
import java.util.Optional;

public class Example {

	public static void main(String[] args) throws IOException {
		Optional<String> optional = Optional.empty();

		System.out.println(optional.orElse("Hello Huong Dan Java"));
	}
}

Result:

Or() methods of Optional object in Java


The second or() method I want to talk about is the orElseGet() method of the Optional object.

The parameter of this method is a Functional Interface Supplier. You can see more information about the Supplier interface here.

The purpose of this method is the same as the orElse() method, but in this case, the default value returned from the Functional Interface Supplier.

For example:

package com.huongdanjava.javaexample;

import java.io.IOException;
import java.util.Optional;

public class Example {

	public static void main(String[] args) throws IOException {
		Optional<String> optional = Optional.empty();

		System.out.println(optional.orElseGet(() -> "Hello Huong Dan Java"));
	}
}

Result:

Or() methods of Optional object in Java


The third method is the or() method.

This method was introduced from Java 9.

The parameter of this method is also a Functional Interface Supplier.

This method always gives us an Optional object that is not empty. If the Optional object is not empty, it returns the Optional object itself, otherwise, it returns the Optional object that the Supplier creates.

For example:

package com.huongdanjava.javaexample;

import java.io.IOException;
import java.util.Optional;

public class Example {

	public static void main(String[] args) throws IOException {
		String s = null;

		Optional<String> opt = Optional.ofNullable(s);
		Optional<String> result = opt.or(() -> Optional.of("Thanh"));

		System.out.println(result);
	}
}

Result:

Or() methods of Optional object in Java

 

The post Or() methods of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/or-methods-optional-object-java.html/feed 0
stream() method of Optional object in Java https://huongdanjava.com/stream-method-optional-object-java.html https://huongdanjava.com/stream-method-optional-object-java.html#respond Tue, 06 Feb 2018 07:11:57 +0000 https://huongdanjava.com/?p=6580 This method is supported since Java 9. This method is used to create a new Stream object from an Optional object in Java. If the Optional object contains a value, this method will return the Stream object containing that value, otherwise, it returns an empty… Read More

The post stream() method of Optional object in Java appeared first on Huong Dan Java.

]]>
This method is supported since Java 9.

This method is used to create a new Stream object from an Optional object in Java.

If the Optional object contains a value, this method will return the Stream object containing that value, otherwise, it returns an empty Stream object.

For example:

package com.huongdanjava.javaexample;

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

public class Example {

	public static void main(String[] args) throws IOException {
		String s = "Khanh";

		Optional<String> opt = Optional.ofNullable(s);
		Stream<String> stream = opt.stream();
		stream.forEach(System.out::println);
	}
}

Result:

stream() method of Optional object in Java

In the case where we have a List of Optional objects, one of them is empty, the stream() method of the Optional object can help us remove these Optional empty objects.

For example:

package com.huongdanjava.javaexample;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) throws IOException {
		List<Optional<String>> names = List.of(
			Optional.of("Khanh"), 
			Optional.empty(), 
			Optional.of("Quan"));

		Stream<String> stream = names.stream().flatMap(Optional::stream);
		stream.forEach(System.out::println);
	}
}

You can refer to the flatMap() method of the Stream object here.

Result:

stream() method of Optional object in Java

 

The post stream() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/stream-method-optional-object-java.html/feed 0
Some ways to initialize Optional object in Java https://huongdanjava.com/some-ways-to-initialize-optional-object-in-java.html https://huongdanjava.com/some-ways-to-initialize-optional-object-in-java.html#respond Tue, 10 Oct 2017 15:16:27 +0000 https://huongdanjava.com/?p=4729 In the previous tutorial, I introduced with you all about the Optional object in Java. In this tutorial, let’s find out some ways to initialize your Optional object in Java. OK … First, we can initialize an Optional object with the nulled reference variable. For… Read More

The post Some ways to initialize Optional object in Java appeared first on Huong Dan Java.

]]>
In the previous tutorial, I introduced with you all about the Optional object in Java. In this tutorial, let’s find out some ways to initialize your Optional object in Java.

OK …

  • First, we can initialize an Optional object with the nulled reference variable.

For example, if you want to initialize an Optional of String object with a nulled String, you would do the following:

Optional<String> opt = Optional.empty();

  • The second is that we will initialize an Optional object with the specified reference variable to an object.

In this way, you must pass a reference variable to the object that already initialized.

String s = new String("Khanh");
Optional<String> opt = Optional.of(s);

If you pass a nullable reference variable, then the NPE error is normal.

Some ways to initialize Optional object in Java

  • The third way is that we can initialize an Optional object with a reference variable that can be null or not.

This is the most common way to create an Optional object. We do not care about the value of the reference variable:

String s = new String("Khanh");
Optional<String> opt = Optional.ofNullable(s);

If it is null then our Optional object is empty.


The post Some ways to initialize Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/some-ways-to-initialize-optional-object-in-java.html/feed 0
Introduction about Optional object in Java https://huongdanjava.com/introduction-about-optional-object-in-java.html https://huongdanjava.com/introduction-about-optional-object-in-java.html#respond Thu, 21 Sep 2017 12:50:06 +0000 https://huongdanjava.com/?p=4226 In the previous tutorial about NullPointerException in Java, I have presented to you some cases where NPE can occur and how to deal with them to avoid. From Java 8, we have another way to avoid NullPointerException, that will use the Optional object. What is… Read More

The post Introduction about Optional object in Java appeared first on Huong Dan Java.

]]>
In the previous tutorial about NullPointerException in Java, I have presented to you some cases where NPE can occur and how to deal with them to avoid. From Java 8, we have another way to avoid NullPointerException, that will use the Optional object. What is it? In this tutorial, we will learn about it together.

OK, let’s get started …

The Optional object is a generic object, which is a container for an object reference. This means that you declare a variable reference to an object, which may or may not have been initialized, and Optional object will contain this variable.

We can see Optional as a stream containing 0 or 1 element as an object reference, 0 if our object reference is null, 1 if our object reference has already been initialized.

This will ensure that when you use our reference variable through the Optional object, the return value is managed by the Optional object and therefore the value of this reference variable will never be null.

Now, I will take an example for you to imagine how to use the object Optional!

Suppose, you have a method used to derive a student’s birthday based on the id you pass on, after handling some business logic, this method returns null. Specifically, the method is as follows:

public Date getDateOfBirth(int studentId) {
	// Do something
	return null;
}

Now, I will use this method and unfortunately it returns null and I get NPE.

Introduction about Optional object in Java

In this case, we can use the Optional object to handle the NullPointerException as follows:

package com.huongdanjava;

import java.util.Date;
import java.util.Optional;

public class Example {
	
	public Date getDateOfBirth(int studentId) {
		// Do something
		return null;
	}

	public static void main(String[] args) {
		Example e = new Example();
		Optional<Date> date = Optional.ofNullable(e.getDateOfBirth(1));
		date.ifPresent(d -> System.out.println(d.getDate()));
	}
}

In this example, we initialized an Optional object containing a variable that references the Date data type, which can be null depend on the value of the getDateOfBirth() method.

And in the code below, I use the ifPresent() method of the Optional object with the Lambda Expression to print the date in case this reference variable is not null.

Try running this example, you will see no more NPE appear.


The post Introduction about Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/introduction-about-optional-object-in-java.html/feed 0