How to implement empty judgment in Java
1. Foreword
In actual projects, we will have many places where null verification is required. If null verification is not performed, NullPointerException may occur. .
Let’s first look at some null judgment methods in actual projects
if (ObjectUtil.isNotNull(vo.getSubmitterId())) { userIds.add(vo.getSubmitterId()); } if (StringUtils.isNotBlank(vo.getBudgetPM())) { userIds.add(Long.valueOf(vo.getBudgetPM())); } if (CollUtil.isNotEmpty(vo.getOriginatorList())) { userIds.addAl1(vo.getOriginatorList().stream(); }
Usually we judge whether an object is Null, you can use Objects in java.util .nonNull(obj), ObjectUtil in hutool or direct null != obj
2. Null judgment of List
Special items like List may not only judge non-null in the project empty. For List, it is not equal to null and List.size() is not equal to 0. There are two different things. Interns in the company often confuse these two. If list is not equal to null, it means that it has been initialized and there is a piece of heap memory that belongs to it. The site, and a size of 0 means that nothing has been put into it. For example, if it is not equal to null, it means that I now have a bottle. If the size is greater than 0, it means that I have filled the bottle with water.
In actual projects, we also found that list.isEmpty() is used directly to judge. Let’s take a look at the source code:
public boolean isEmpty() { return size == 0; }
It is equivalent to judging whether there is water in the bottle (provided that the bottle already exists, If the bottle does not exist, a NullPointerException will be thrown).
So usually list != null && list.size > 0 is used to judge, or directly use isEmpty of the CollUtil tool in HuTool. There are also Set, Map, etc.
3. String null judgment
The concepts of bottles and water are still used here. When String is null, operations such as equals(String) or length() are called. Throws java.lang.NullPointerException.
There are several ways to detect the empty string:
1. One of the methods used by most people, intuitive and convenient, but inefficient :
if(a == null || a.equals(""));
2. Compare string lengths, efficient:
if(a == null || a.length() == 0);
3. Java SE 6.0 has just started to be provided, and the efficiency is almost the same as method two:
if(a == null || a.isEmpty());
Of course, you can also use the org.apache.commons.lang.StringUtils tool.
StringUtils.isNotBlank(a);
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
There is also an isNotEmpty() method in this tool class. The difference between the two can be clearly seen from the comments
StringUtils.isNotEmpty(a);
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
4. The appearance of Optional
Optional is used Prevent NullpointException. Common methods are:
.empty(): Create an empty Optional instance
.of(T t): Create an Optional Instance, an exception will be reported if it is null
.ofNullable(T t): If t is not null, create an Optional instance, otherwise create an empty instance
isPresent(): Determine whether there is a value in the container
ifPresent(Consume lambda): If the container is not empty, execute the Lambda expression in the brackets
orElse(T t): Get the element in the container. If the container is empty, return the default value in the brackets
orElseGet(Supplier s): If the calling object contains a value , return the value, otherwise return the value obtained by s
orElseThrow(): If it is empty, throw the defined exception, if not, return the current object
map(Function f): If there is a value, process it and return the processed Optional, otherwise return Optional.empty()
flatMap(Function mapper ): Similar to map, the return value must be Optional
T get(): Get the element in the container, if the container is empty, a NoSuchElement exception will be thrown
Let’s look at a common example first:
There is a Boolean type attribute in the baseInfo class. If it is empty, it returns false. If it is not empty, it takes its value, which requires four lines.
boolean blind = false; if (null != baseInfo.getBlind()){ blind = baseInfo.getBlind(); }
When using Optional, it can be done in one line, very elegant.
boolean blind = Optional.ofNullable(baseInfo.getBlind()).orElse( other: false);
4.1 Creation of Optional objects
public final class Optional<T> { private static final Optional<?> EMPTY = new Optional<>(); private final T value; //可以看到两个构造方格都是private 私有的 //说明 没办法在外面new出来Optional对象 private Optional() { this.value = null; } private Optional(T value) { this.value = Objects.requireNonNull(value); } //这个静态方法大致 是创建出一个包装值为空的一个对象因为没有任何参数赋值 public static<T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; } //这个静态方法大致 是创建出一个包装值非空的一个对象 因为做了赋值 public static <T> Optional<T> of(T value) { return new Optional<>(value); } //这个静态方法大致是 如果参数value为空,则创建空对象,如果不为空,则创建有参对象 public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); } }
4.2 Usage scenarios
Scenario 1: Query an object in the service layer, and after returning, determine whether it is empty and process it
Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); Optional.ofNullable(task).orElseThrow(() -> new ProcessException(ErrorCodeEnum,SYSIEM ERROR));
Scenario 2: Using Optional and functional programming, done in one line
Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); Map<String,String> map = new HashMap<>( initialCapacity: 8); Optional.ofNullable(task).ifPresent(d -> map.put("taskId",d.getTaskDefinitionKey()));
The above is the detailed content of How to implement empty judgment in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
