
1. preface
for Java For developers,null
It's a troublesome type that can happen if you're not careful NPE (Empty pointer) problem. is also Java One of the important reasons why language is criticized. Before we eliminate the hateful NPE Before we ask, we want to review the concept of null in Java.
2. null in Java
translated from Oracle Java Documentation
There are two types in the Java language, one is basic types , the other is reference type。There is also a special type that has no name, namely expression
null
。
due tonull
Types have no names, so it is impossible to declare asnull
variable of type or converted tonull
Type.null
reference isnull
The only possible value for a type expression.null
References can be converted to any reference type.
In fact, programmers can ignorenull
Type, can be considerednull
Just a special symbol that can be any reference type.
We can understand from the above description,In fact, null is just a keyword identifier. It is neither a type nor an object. It cannot be directly declared null and converted to null. It can only be referenced. null can be converted to any reference type. When a Java reference type object is referenced as null, it means that the current object does not reference the object and no memory is allocated for it. This is also the root cause of empty pointers when we call methods on objects without reference.
in most cases Java developers to use null
It's meant to mean something that doesn't exist.
3. Solving NPE problems
Many times we have our own expectations about whether data exists, but this expectation cannot be directly controlled by us. The meaning expressed by a return value of null is not clear and too vague. It is often determined by whether or not null
to avoid the empty pointer problem. So Google engineers worked on their Guava
Tools class library designed Optional<T>
to solve null
Uncontrollable problems. that allows you to use null
When, it can be used more easily and clearly null
and help you avoid direct use null
Problems brought.
Java 8 Incorporate this design. we can directly use Java provided Optional
to solve the empty pointer problem. Next let's study Java 8 of Optional
。
4. Optional in Java 8
in Java 8 Optional
Is a wrapper class for optional values. It doesn't just help us simplify NPE Dealing with problems, but also Java An important aid to functional programming. We're going to take it API Provide explanations to help you use them in actual development.
4.1 Optional Statement
Optional
Declarations can only be made through static methods. It provides three static methods:
empty() Returns a value of null
the Optional
examples
Optional<Object> empty = Optional.empty();
of(T) Returns a value that is not null
the Optional
examples
Optional<String> nonNull = Optional.of("Felordcn");
ofNullable() Returns a value that may be null
the Optional
examples
// value comes from other uncertain sources
String value = SomeApi.source();
//may be null
Optional<String> nullable = Optional.ofNullable(value);
//may not be null
Optional<String> hasValue = Optional.ofNullable(value);
4.2 other methods
isPresent() Returns if value exists true
, otherwise return false
。if Optional
Value is uncertain, this method can be used for safety verification
Optional<String> nonNull = Optional.of("Felordcn");
// true
boolean present =nonNull.isPresent();
get() obtain Optional
If it is empty, it will be thrown NoSuchElementException
abnormal
// value comes from other uncertain sources
String value = SomeApi.source();
//may be null
Optional<String> nullable = Optional.ofNullable(value);
// Felordcn
String str = nullable.get();
ifPresent(Consumer) If a value exists, the value is consumed by the function Consumer
Consumption, otherwise do nothing. isPresent()
enhanced version
//Print the string without blank
nullable.ifPresent(System.out::println);
//equivalent to
if (nullable.isPresent()) {
System.out.println(nonNull);
}
filter(Predicate) If the value satisfies the assertion function Predicate
Return the Optional
, otherwise return Optional.empty()
Optional<String> nonNull = Optional.of("Felordcn");
Optional<String> felord = nonNull.filter(s -> s.startsWith("Felord"));
// str = "Felordcn"
String str = felord.get();
map(Function) Gets the attribute of an element Optional
。if the property is null
return Optional.empty()
, otherwise return the corresponding value of Optional
Optional<User> userOpt = Optional.ofNullable(user);
//If username is empty, it will be empty Optional
Optional<String> usernameOpt = userOpt.map(User::getUsername);
flatMap(Function) Sometimes we return Optional<Optional<T>>
It is very inconvenient to handle. We need to expand the element. We can use this method to handle it. Refer to Stream Api the relevant method specified in
orElse(other) if Optional
value exists, return Optional
, otherwise specify one Optional
orElseGet(Supplier) if Optional
value exists, return Optional
, otherwise specify an execution Supplier
Function to get the value
orElseThrow(Supplier<? extends Throwable>) if Optional
value exists, return Optional
, otherwise throw a specified Supplier
Exception provided by function
4.3 New APIs in Java 9
or(Supplier) orElseGet
Types of improvements. Not only return specific values, but you can return them functionally Optional
stream() will Optional
and Stream
open up
ifPresentOrElse(Consumer) ifPresent
Methods provide consumption logic with values, while logic without values provides no entry. new method ifPresentOrElse
it makes up for
5. Misunderstandings of Optional
Optional
It smells good but you can't abuse it. A dangerous move is to Optional
Passed to the method as an input parameter. Because the entry is uncontrollable, you cannot guarantee the entry Optional
whether it is null
。This is exactly contrary to Optional
the original intention. So try to use it in expressions Optional
or use it in the return value rather than in the parameters of the method Optional
。
6. summary
today Optional
Give an explanation. from Optional
The design intention is based on its common methods. We are also interested Optional
in Java 9 The new API in. in addition Optional
It is not a panacea, and only through reasonable use can its advantages be given full play. I hope today's article is useful to you.
Comments0