Home > Java > javaTutorial > body text

Share the example code of the newly introduced class Optional in Java8

零下一度
Release: 2017-05-24 11:41:38
Original
2030 people have browsed it

Optional is a newly introduced class in Java8
This is a container that can be null object. If the value exists, the isPresent() method will return true, and calling the get() method will return the object.
java.lang.NullPointerException, as long as you dare to call yourself a Java programmer, you will be very familiar with this exception. In order to prevent this exception from being thrown, we often write code like this:

Person person = people.find("John Smith");
if (person != null) {
 person.doSomething();
}
Copy after login

Unfortunately, in most Java codes, we often forget to judge null references, so NullPointerException is It also followed.
"Null Sucks." This is Doug Lea's evaluation of null. As a Java programmer, if you still don’t know who Doug Lea is, then hurry up and make up the lessons. Without his contribution, we can only use Java’s most primitive equipment to handle multi-threading.
"I call it my billion-dollar mistake.", who is qualified to say this is the inventor of the null reference, Sir C. A. R. Hoare. You don't have to know Doug Lea, but you must know this old man, otherwise, you are not qualified to use quick sort.
In the Java world, a common way to solve the null reference problem is to use the Null Object mode. In this case, in the case of "nothing", Null Object is returned, and the client code does not need to judge whether it is empty. However, there are some problems with this approach. First, we definitely have to write code for Null Object, and if we want to apply this pattern at scale, we have to write Null Object for almost every class.

Fortunately, we have another option: Optional. Optional is an encapsulation of nullable objects, and it is not complicated to implement. In some languages, such as Scala, Optional implementation becomes part of the language. For Java programmers, Guava provides us with Optional support. Without further ado, let’s first talk about how to use Optional to complete the previous code.

Optional person = people.find("John Smith");
if (person.isPresent()) {
 person.get().doSomething();
}
Copy after login

If isPresent() returns false here, it means that this is an empty object. Otherwise, we can take out the content and do what we want to do.
If you are looking forward to a reduction in code size, I am afraid you will be disappointed here. In terms of code size alone, Optional even has more code than the original. But the good thing is that you will never forget to check for null, because what we get here is not an object of the Person class, but an Optional.
The following is the code for personal practice

public class OptionalTest {
	/**
	 * of后面接给optional设置的值 但是不能为空 如果为空会报空指针异常
	 * @Title: ofTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void ofTest()
	{
		Optional<String> optional = Optional.of("123");
		System.out.println(optional.get());
		try
		{
			optional = Optional.of(null);
			System.out.println(optional.get());  //get方法是获取optional的值 类型取决于声明的时候
		}catch(NullPointerException e)
		{
			System.out.println("空指针异常");
		}
	}
	/**
	 * ofNullable 和of类似 但是ofNullable可以设置null值  如果是Null值得话取值会报NoSuchElementException 异常
	 * @Title: ofNullableTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void ofNullableTest()
	{
		Optional<String> optional = Optional.ofNullable("123");
		System.out.println(optional.get());
		try
		{
			optional = Optional.ofNullable(null);
			System.out.println(optional.get());
		}catch(NoSuchElementException e)
		{
			System.out.println("NoSuchElementException 异常");
		}
	}
	
	/**
	 * ifPresent用来判断optional中有没有值存在 如果有则为真
	 * @Title: isPresentTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void isPresentTest()
	{
		Optional<String> optional =  Optional.ofNullable(null);
		if(optional.isPresent())
		{
			System.out.println(optional.get());
		}
		else
		{
			System.out.println("值为空");
		}
	}
	/**
	 * ifPresent和isPresent类似 只不过它支持λ表达式
	 * @Title: ifPresentTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void ifPresentTest()
	{
		Optional<String> optional =  Optional.ofNullable("123");
		optional.ifPresent(var ->{
			System.out.println(var);
		});
	}
	
	/**
	 * orElse方法,如果值为空的话会用参数中的值去替换 即设置默认值
	 * @Title: orElseTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void orElseTest()
	{
		Optional<String> optional =  Optional.ofNullable("123");
		System.out.println(optional.orElse("有没有"));
		optional = Optional.ofNullable(null);
		System.out.println(optional.orElse("有没有"));
	}
	/**
	 * orElseGet方法 和orElse类似 不过此方法接受Supplier接口的实现用来生成默认值
	 * @Title: orElseGetTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void orElseGetTest()
	{
		Optional<String> optional =  Optional.ofNullable("123");
		System.out.println(optional.orElseGet(()->"123456"));
		optional = Optional.ofNullable(null);
		System.out.println(optional.orElseGet(()->"123456"));
	}
	/**
	 * map方法  如果有值则会对值进行mapping中的处理 处理结果存在则创建并返回Optional类型的结果 否则返回空
	 * @Title: mapTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void mapTest()
	{
		Optional<String> optional =  Optional.ofNullable("abc");
		System.out.println(optional.map(var->var.toUpperCase()).get());
	}
	/**
	 * flatMap和map类似 只不过mapping中必须返回Option类型的数据
	 * @Title: flatMapTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
//	@Test
	public void flatMapTest()
	{
		Optional<String> optional =  Optional.ofNullable("abc");
		System.out.println(optional.flatMap(var->Optional.of(var.toUpperCase())).get());
	}
	/**
	 * filter对optional进行过滤,mapping中为过滤的条件  如果不满足条件 返回一个为空的Optional
	 * @Title: filterTest
	 * @Description: TODO
	 * @param: 
	 * @return: void
	 * @throws
	 */
	@Test
	public void filterTest()
	{
		try
		{
			Optional<String> optional = Optional.ofNullable("一二三四五六七八");
			System.out.println(optional.filter(var ->var.length()>6).get());
			System.out.println(optional.filter(var ->var.length()<6).get());
		}catch(NoSuchElementException e)
		{
			System.out.println("optional的值为空");
		}
	}
Copy after login

[Related recommendations]

1. Usage examples of Java 8’s new API--Optional

2. Parsing Java 8 Optional Class Instance Tutorial

The above is the detailed content of Share the example code of the newly introduced class Optional in Java8. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!