[JAVA] About Optional

What is Optional

The one that can have null. that's all.

In detail

There's a null scary illness about things like models and objects. So, if there is an Entity class called KWSK You can handle null by making it Optional .

Concrete example

Optional.java


package optional;

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

public class Practice {

	public static void main(String[] args) {
		//Initialization of Optional
		Optional<String> empty = Optional.empty();
		// Optional<String>To String(Take out the contents)
		String str = empty.get();
		//Make sure it has a value, not null
		empty.isPresent(); // false

		System.out.println(run("a"));
		System.out.println(run2("a"));
	}

	/**
	 *Returns an argument<br>
	 *Returns an empty string if the argument is null
	 * 
	 * @param str
	 * @return
	 */
	private static String run(String str) {
		return Optional.ofNullable(str).orElse("");
	}

	/**
	 *Returns an argument<br>
	 *NoSuchElementException occurs when the argument is null(get()Because the method cannot be done)
	 * 
	 * @param str
	 * @return
	 */
	private static String run2(String str) {
		return Optional.of(str).get();
	}

	/**
	 *You can also use filters and maps like streams
	 *You can also use stream
	 * 
	 * @param str
	 */
	private static void run3(String str) {
		Optional.ofNullable(str).filter(v -> v.length() == 1).isPresent();
		Optional.ofNullable(str).map(v -> v + "2").isPresent();

		List<Optional<String>> list = new ArrayList<Optional<String>>();
		list.add(Optional.of("a"));
		list.add(Optional.of("b"));
		list.add(Optional.of("c"));
		list.add(Optional.empty());

		list.stream().filter(Optional::isPresent).map(Optional::get).forEach(System.out::println);
	}

}

is.

So what's convenient?

I've put it together in the code So what I mean is a null expert

When dealing with any model, if you wonder what to do with null, please think of Optional for the time being.

Optional.ofNullable(The one who wants to judge null).orElse("");

In the get () method when restoring from the Optional type, NoSuchElementexception will appear if you are not careful. You can overcome the basic null scary illness if you do it thoroughly!

Since conditional branching in boolean of ʻisPresent` method is convenient for null in stream soon. It's easy just to attach it to a null scary system such as findFirst

Objects::nonNull

Or

Objects::toString

But it seems that it can be handled, but the Objects type seems to be a last resort. I don't know the detailed reason why Optional is better. It feels like you don't have to do that.

Optional Official Reference Objects Official Reference

Recommended Posts

About Optional
About =
About method.invoke
About Kotlin
About attr_accessor
About Hinemos
About inheritance
About params
About Docker
About Rails 6
About form_for
About Spring ③
About enum
About polymorphism
About hashes
About JitPack
About Dockerfile
About this ()
About devise
About encapsulation
About Docker
About JAVA_HOME
About active_hash
About static
About exceptions
Think about the 7 rules of Optional
About scope
[Maven] About Maven
About exception handling
Review about bundler
About Java interface
[Java] About Java 12 features
About Rails routing
About cyclomatic complexity
About AsyncTask Generics
About Ruby symbols
About array multiplication
[Java] About arrays
About HotSpot VM
About ruby ​​form
[Swift] About generics
About Active Storage
Java Optional type
About class inheritance.
About Spring AOP
About Ruby Hashes
About singular methods
About getter setter
About build tools
About MacinCloud introduction
[Note] About nil
Studying Java 8 (Optional)
Chew about API
[About double hash]
About installing Cocoapods
Something about java
Where about java
About HttpServlet () methods
About Java features
About ActiveRecord :: PendingMigrationError
About SIGNING_REGION: NoSuchFieldError