


Optional class in Java 8: How to filter possibly null values using filter() method
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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

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),

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor