search
HomeJavajavaTutorialHow 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

    How to implement empty judgment in Java

    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.

    How to implement empty judgment in Java

    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!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

    Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

    What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

    Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

    How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

    Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

    How does Java's platform independence facilitate code reuse?How does Java's platform independence facilitate code reuse?Apr 24, 2025 am 12:05 AM

    Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

    How do you troubleshoot platform-specific issues in a Java application?How do you troubleshoot platform-specific issues in a Java application?Apr 24, 2025 am 12:04 AM

    To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

    How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

    The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

    Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

    The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

    How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

    Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),