Home> Java> javaTutorial> body text

How to implement empty judgment in Java

王林
Release: 2023-05-13 16:34:06
forward
1007 people have browsed it

    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(); }
    Copy after login

    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; }
    Copy after login

    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(); }
    Copy after login

    When using Optional, it can be done in one line, very elegant.

    boolean blind = Optional.ofNullable(baseInfo.getBlind()).orElse( other: false);
    Copy after login

    4.1 Creation of Optional objects

    public final class Optional { 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 Optional empty() { @SuppressWarnings("unchecked") Optional t = (Optional) EMPTY; return t; } //这个静态方法大致 是创建出一个包装值非空的一个对象 因为做了赋值 public static  Optional of(T value) { return new Optional<>(value); } //这个静态方法大致是 如果参数value为空,则创建空对象,如果不为空,则创建有参对象 public static  Optional ofNullable(T value) { return value == null ? empty() : of(value); } }
    Copy after login

    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));
    Copy after login

    Scenario 2: Using Optional and functional programming, done in one line

    Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); Map map = new HashMap<>( initialCapacity: 8); Optional.ofNullable(task).ifPresent(d -> map.put("taskId",d.getTaskDefinitionKey()));
    Copy after login

    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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!