Home >Java >javaTutorial >Optional class in Java 8: How to filter possibly null values ​​using filter() method

Optional class in Java 8: How to filter possibly null values ​​using filter() method

王林
王林Original
2023-08-01 17:27:231492browse

Optional class in Java 8: How to filter possibly empty values ​​using the filter() method

In Java 8, the Optional class is a very useful tool that allows us to better handle possible A null value avoids the occurrence of NullPointerException. The Optional class provides many methods to manipulate potential null values, one of the important methods is filter().

The function of the filter() method is that if the value of the Optional object exists and meets the given conditions, the Optional object itself is returned; if the value does not exist or the conditions are not met, an empty value is returned. Optional object.

The following code example demonstrates how to use the filter() method to filter potentially empty values:

import java.util.Optional;

public class OptionalFilterExample {

    public static void main(String[] args) {
        String name = "John Doe";
        Optional<String> nameOptional = Optional.ofNullable(name);

        // 使用filter()方法过滤值为空的Optional对象
        Optional<String> filteredOptional = nameOptional.filter(n -> n.length() > 5);

        if (filteredOptional.isPresent()) {
            System.out.println("Name is longer than 5 characters");
        } else {
            System.out.println("Name is either null or shorter than 5 characters");
        }
    }
}

In the above example, we first create a non-empty Optional object nameOptional, Its value is "John Doe". Then, we use the filter() method, passing the condition n -> n.length() > 5 to it. This condition checks if the length of the string is greater than 5. If the condition is met, the filter() method returns an Optional object containing the same value; otherwise, it returns an empty Optional object.

Finally, we use the isPresent() method to check whether the filtered Optional object contains a value, and output the corresponding information based on the result.

In actual development, we often need to filter out values ​​that may be empty. Using the filter() method, we can accomplish this task concisely. Here is another example that demonstrates how to filter out integers greater than 10 in a list:

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class OptionalFilterListExample {

    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(15);
        numbers.add(8);
        numbers.add(20);

        List<Integer> filteredNumbers = new ArrayList<>();

        for (Integer number : numbers) {
            Optional<Integer> optionalNumber = Optional.ofNullable(number);
            optionalNumber.filter(n -> n > 10).ifPresent(filteredNumbers::add);
        }

        System.out.println(filteredNumbers);
    }
}

In the above example, we first created an integer list numbers, which contains some numbers. We then use a for-each loop to iterate over each element in the list and wrap them into Optional objects.

Next, we use the filter() method to filter out numbers greater than 10, and use the ifPresent() method to add the filtered numbers to the filteredNumbers list.

Finally, we output the filteredNumbers list, which contains all filtered numbers.

By using the filter() method of the Optional class, we can filter possible null values ​​more concisely, avoiding cumbersome null checks and situations that may lead to NullPointerException. This makes our code more robust and readable. It is recommended to make full use of various methods of the Optional class in development to improve code quality and development efficiency.

The above is the detailed content of Optional class in Java 8: How to filter possibly null values ​​using filter() method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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