[Java] How to use Optional ②

Programming study diary

January 2, 2021 Yesterday's article Similarly, I will briefly summarize how to use Java's Optional class. I will introduce how to use it with a method that I did not deal with yesterday.

How to use the orElseThrow method

The orElseThrow method processes differently depending on the presence or absence of arguments.

If there is no argument, it throws NoSuchElementException when it is null and returns a value when it is not null.

With no arguments


import java.util.NoSuchElementException;
import java.util.Optional;
 
public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        try {
            str = value.orElseThrow();
            System.out.println(str);
        } catch (NoSuchElementException ex) {
            System.out.println("null");
        }
    }
}

Execution result


null

If there is an argument, you can specify an object of exception class through which the exception is passed.

With arguments


import java.util.Optional;
 
public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        try {
            System.out.println(value.orElseThrow(() -> new RuntimeException()));
        } catch (RuntimeException e) {
            System.out.println("null");
        }    
    }
}

Execution result


null

How to use the stream method

It is possible to extract only non-null objects from Optional type objects without checking for null.

import java.util.List;
import java.util.Optional;
 
public class Sample {
    public static void main(String[] args) {
        List<String> list1 = List.of("Tanaka", "Yamada");
        List<String> list2 = null;
        
        Optional<List<String>> value1 = Optional.ofNullable(list1);
        Optional<List<String>> value2 = Optional.ofNullable(list2);
        
        value1.stream().flatMap(x -> x.stream()).forEach(System.out::println);
        value2.stream().flatMap(x -> x.stream()).forEach(System.out::println);
    }
    
}

Execution result


Tanaka
Yamada

How to use the ifPresent method

Performs the process specified in the argument only when it is not null.

import java.util.Optional;
 
public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        value.ifPresent(System.out::println);
    }
 
}

Execution result


No processing is done because str is null

How to use the ifPresentOrElse method

Processing can be performed even if it is null. Specify the processing when it is not null in the first argument, and specify the processing when it is null in the second argument.

import java.util.Optional;
 
public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        value.ifPresentOrElse(
            System.out::println, 
            () -> System.out.println("null"));
    }
 
}

Execution result


null

References

How to use Optional class in Java [For beginners] What is Java Optiona? Easy-to-understand explanation of how to use each pattern

Recommended Posts

How to use java Optional
[Java] How to use Optional ②
[Java] How to use Optional ①
[Java] Learn how to use Optional correctly
[Java] How to use Map
How to use java class
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
How to use Java variables
How to use Java HttpClient (Post)
[Java] How to use join method
[Processing × Java] How to use variables
[Java] How to use LinkedHashMap class
[JavaFX] [Java8] How to use GridPane
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
Multilingual Locale in Java How to use Locale
How to use Map
[Java] How to use the File class
[Java] How to use the hasNext function
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use submit method (Java Silver)
[Java] How to use the HashMap class
How to use collection_select
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use Java classes, definitions, import
[Easy-to-understand explanation! ] How to use Java polymorphism
[Java] [Maven3] Summary of how to use Maven3
[Processing × Java] How to use the class
How to use Java Scanner class (Note)
How to use JUnit 5
[Processing × Java] How to use the function
[Easy-to-understand explanation! ] How to use ArrayList [Java]
How to use Dozer.mapper
[Java] How to use the Calendar class
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
[Easy-to-understand explanation! ] How to use Java overload
How to use Map
try-catch-finally exception handling How to use java