The one that can have null. that's all.
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
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.
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