Wednesday, August 22, 2018

java8 - Top 10 Optional Class Examples

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

Optional Class Tutorials
OptionalInt class Examples
OptionalLong class Examples
OptionalDouble class Examples

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

java.util.Optional Examples

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

Following are the Optional Class How to examples

Convert List to Optional<List> 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

Integer[] numbersArray = { 1, 2, 3, 4, 5, 6, 7 };
List<Integer> integers = new ArrayList<Integer>(Arrays.asList(numbersArray));
Optional<List<Integer>> listIntegersOptional = Optional.of(integers);
listIntegersOptional.ifPresent((list) -> {
 System.out.println(list.size()); // output 
});

Convert List to List<Optional> java8

This is an example for converting List<Integer> to List<Optional<Integer>> in java8.Using stream() with a lambda expression, map each element and Wrap in Optional class using the collect method
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());

Convert Optional String to String

First Create Optional String using ofNullable. You can also create an Optional instance using of() method.
Difference between Of() and ofNullable()
of(), if value is null, Null pointer exception is thrown
ofNullable() if value is null, return Empty Optional Instance
Once instance is created, get() method convert optional string to string object.
Optional<String> optionalString1=Optional.ofNullable("testoptionalstring");
String string=optionalString1.get();
System.out.println(string);

Convert String to Optional String

ofNullable() method will convert normal Object to Optional Object type.
String str="kiran";
Optional<String> optionalString=Optional.ofNullable(str);
System.out.println(optionalString.isPresent());
optionalString.ifPresent(value->{
        System.out.println(value);
});

This below example explains about usage and conversion.

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
This is an example of Converting Optional to Stream in java8

String str="kiran";
Optional<String> optionalString=Optional.ofNullable(str);
Stream<String> streamString = optionalString.isPresent() ? Stream.of(optionalString.get()) : Stream.empty();

Convert Optional<Integer> to Optional<Long> 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
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

This is a simple way of usage of Optional and it's utility methods.
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 is
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.
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 is
one
two
three
four

Related article


EmoticonEmoticon