{

java8 - Best 10 Optional Class Examples


java8 - Top 10 Optional Class Examples

In my previous post, We covered the following articles about Optional classes and examples in Java 8

You may like other posts on java 8

Now you got an understanding of the basics and usage of Optional classes.

The optional class is a container object for holding null or not null values.

Following are the Optional Class How to examples.

How to Convert List to Optional in java8?

  • First, Converted Array to List using Arrays.asList() method
  • Optional.of(list) method creates Optional List with non empty values.
  • This converted list to Optional List.
  • Using ifPresent() method and lambda expression, returned the size of Optional List

Here is an example

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

public class Test {
    public static void main(String[] args)  throws Exception{
        Integer[] numbersArray = { 1, 2, 3, 4, 5, 6, 7 };
        List<Integer> integers = new ArrayList<>(Arrays.asList(numbersArray));
        Optional<List<Integer>> listIntegersOptional = Optional.of(integers);
        listIntegersOptional.ifPresent((list) -> {
            System.out.println(list.size()); // output
        });

    }
}

How to Convert List to List java8?

This is an example for converting List to List<Optional> in java8.

Using stream() with a lambda expression, map each element and Wrap in the Optional class using the collect method.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class CovertOptionalList {
    public static void main(String[] args)  throws Exception{
        Integer[] numbersArray = { 1, 2, 3, 4, 5, 6, 7 };
        List<Integer> integerList = new ArrayList<Integer>(Arrays.asList(numbersArray));
        List<Optional<Integer>> listOptionalIntegers =
                integerList.stream()
                        .map(Optional::ofNullable)
                        .collect(Collectors.toList());
    }
}

How to Convert Optional String to String

First, Create an Optional String using the ofNullable method.

Alternatively, you can create Optional instance using the of() method.

Difference between Of() and ofNullable() in java8

of(), if value is null, Null pointer exception is thrown. ofNullable() if value is null, return Empty Optional Instance

Once an instance creates, the get() method converts an optional string to a string object.

import java.util.Optional;

public class Test {
    public static void main(String[] args)  throws Exception{
        Optional<String> optionalString1=Optional.ofNullable("testoptionalstring");
        String string=optionalString1.get();
        System.out.println(string);
    }
}

How to Convert String to Optional String

ofNullable() method will convert normal Object to Optional Object type.

import java.util.Optional;

public class ConvertOptionalString {
    public static void main(String[] args)  throws Exception{
        String str="kiran";
        Optional<String> optionalString=Optional.ofNullable(str);
        System.out.println(optionalString.isPresent());
        optionalString.ifPresent(value->{
            System.out.println(value);
        });
    }
}

The below example explains usage and conversion.

How to Convert Optional to Stream of type Object in java8?

Optional is a container for holding non-empty and empty values.
Stream class is a for processing data for aggregation result
It is an example of Converting Optional to Stream in java8

import java.util.Optional;
import java.util.stream.Stream;

public class OptionalStreamExample {
    public static void main(String[] args)  throws Exception{
        String str="kiran";
        Optional<String> optionalString=Optional.ofNullable(str);
        Stream<String> streamString = optionalString.isPresent() ? Stream.of(optionalString.get()) : Stream.empty();

    }
}

How to Convert Optional to Optional in java8?

  • First, created Optional Integer using ofNullable()method.
  • check value exists using isPresent() method, if value exists, get the values using get() method and convert to long value, pass this to Optional.ofNullable() to create a Optional Long object.
import java.util.Optional;

public class OptionalIntegerToLongExample {
    public static void main(String[] args)  throws Exception{
        Optional<Integer> optionalInteger=Optional.ofNullable(123);
        Optional<Long> optionalLong = Optional.ofNullable(optionalInteger.isPresent() ?
                optionalInteger.get().longValue() : null);
    }
}

Concatenate two or more Optional Strings into Optional Strings in java8

It is a simple way of the usage of Optional and its utility methods.

import java.util.Optional;

public class Test {
    public static void main(String[] args)  throws Exception{
        Optional<String> one = Optional.ofNullable("one");
        Optional<String> two = Optional.ofNullable("two");
        Optional<String> output;
        output = one.isPresent() && two.isPresent() ? Optional.of(one.get() + two.get()) : Optional.empty();
        System.out.println(output.get());

    }
}

Output:

onetwo  

How to remove Empty null Optional values from ArrayList?

First Create an ArrayList with optional values of null, empty, and not null values.
We will remove empty/null values from arrays using filter, map, collectors with a lambda expression.

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

public class Test {
    public static void main(String[] args)  throws Exception{
        List<Optional<String>> listOptionalStrings = new ArrayList<>();
        listOptionalStrings.add(Optional.of("one"));
        listOptionalStrings.add(Optional.empty());
        listOptionalStrings.add(Optional.of("two"));
        listOptionalStrings.add(Optional.of("three"));
        listOptionalStrings.add(Optional.empty());
        listOptionalStrings.add(Optional.of("four"));
        listOptionalStrings.add(Optional.ofNullable(null));
        List<String> stringList = listOptionalStrings.stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
        stringList.forEach((value) -> {
            System.out.println(value);
        });
    }
}

Output:

one  
two  
three  
four  

Conclusion

You learned multiple examples in the Optional class with a step-by-step guide.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.