Get the App
SLTechnology News&Howtos  ›  Development  › 

How to determine null traversal by JDK8

Shulou Source: shulou.com Published: 2022-06-02 01:31:19 10月02日 Update

Editor to share with you how to JDK8 empty traversal, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

In the work, often deal with a variety of variables, but often in the use of variables, to make an empty judgment, otherwise an error will be reported.

Java 8 provides the method of writing null:

Optional.ofNullable (variable) .orElse (default)

Example 1: find the length of the string s (return 0 if empty).

Conventional writing:

String s = getKey (); if (s = = null) {return 0;} else {return s.length ();}

Java 8 is written:

String s = getKey (); return Optional.ofNullable (s) .orElse (") .length ()

Example 2: loop through the collection

Conventional writing:

List list = getList (); if (list! = null) {for (String s: list) {System.out.println (s);}}

Java 8 is written:

List list = getList (); Optional.ofNullable (list) .orElse (new ArrayList ()) .forEach (o-> {System.out.println (o);})

PS: use Optional to avoid NullPointerException caused by null

Null pointer exceptions are the most common cause of Java application failure. In the past, to solve null pointer exceptions, Google's famous Guava project introduced the Optional class. Guava prevents code contamination by checking null values, which encourages programmers to write cleaner code. Inspired by Google Guava, the Optional class has become part of the Java 8 class library. Optional is actually a container: it can hold the value of type T, or just null. Optional provides a lot of useful methods so that we don't have to explicitly detect null values.

Optional.of () or Optional.ofNullable (): create an Optional object, the difference being that of does not allow the argument to be null, while ofNullable has no restrictions.

/ / Parameter cannot be nullOptional optional1 = Optional.of (1); / / Parameter can be nullOptional optional2 = Optional.ofNullable (null); / / Parameter can be non-nullOptional optional3 = Optional.ofNullable (2)

The above is all the contents of the article "how to check empty traversal by JDK8". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Writing parameters variables articles code content general pointers time programs clean famous not much not company reasons most characters strings actual Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MySQL vpn NVidia Huawei