Home > Java > javaTutorial > body text

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

王林
Release: 2023-08-01 17:27:23
Original
1379 people have browsed it

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

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

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
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!