Thursday, February 16, 2017

Java 8 Optional examples and usage

        Why OptionalUse it with streams , use it in your return types, make your code safer against to the NPE, make your code more readable...This allows the caller to continue a chain of fluent method calls.

And NoteThe key here is the focus on use as a return type. The class is definitively not intended for use as a property of a Java Bean. Witness to this is that Optional does not implement Serializable, which is generally necessary for widespread use as a property of an object.


If you really wonder what will change in your life with this new Stolen keyword (from Guava) you'd better to read its origin.

More code & less bullshit.. Lets see its usage then..







package com.company.samples.optional;
import com.company.samples.way10.Worker;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
#### There are few ways of creating Optional ###
opt = Optional.of(notNull); will throw exception if it is null
 
opt = Optional.ofNullable(mayBeNull);
 
opt = Optional.empty();
Usages of the Optional.X -> : of (), ofNullable (), empty (), get (), map (), filter (), ifPresent (), orElse ()
*/
public class OptionalTester {
public static void main (String[] args) {
Optional<Worker> workerOptional = getSomeBeanFromSomeWhere ();
Optional<Worker> nullWorkerOptional = getSomeNullBeanFromSomeWhere ();
// # 1) ifpresent -> alternative for if null check
nullWorkerOptional.ifPresent (w -> System.out.println ("ifPresent->worker" + w));
workerOptional.ifPresent (w -> System.out.println ("ifPresent->worker" + w));
// # 2) get -> // will throw an exc if optional is empty
try {
// this line will cause an java.util.NoSuchElementException: No value present
Worker worker = nullWorkerOptional.get ();
System.out.println ("get-> nullworker = " + worker);
} catch (Exception e) {
e.printStackTrace ();
//will print stackTrace of java.util.NoSuchElementException: No value present
}
try {
Worker worker = workerOptional.get ();
System.out.println ("get-> nonNullworker = " + worker);// will print this line
} catch (Exception e) {
e.printStackTrace ();
// this will not throw exception cause it is not null
// but as a programmer you should use try/catch with optional.get
}
// # 3) get -> // provide something other if it is empty , equivalent of the if( worker == null){ return alternativeWorker;}
Worker worker = nullWorkerOptional.orElse (alternativeWorkerFromSomeWhereElse ());
System.out.println ("orElse-> nullWorker = " + worker);
worker = workerOptional.orElse (alternativeWorkerFromSomeWhereElse ());
System.out.println ("orElse-> nonNull = " + worker);
// # Optional + filter usage, equivalent of the if( worker == null && !name.equals ( "Logan")){ print (wroker);}
boolean notLoganFound = workerOptional.filter (w -> w.getName ().equals ("Logan")).isPresent ();
System.out.println ("filter-> compare = " + notLoganFound);
notLoganFound = workerOptional.isPresent () && !workerOptional.get ().getName ().equals ("Logan");
System.out.println ("filter-> compare = " + notLoganFound);
// # Optional + map usage, check and transform the data
workerOptional.map (w -> {
w.setName ("animal");
return w;
}).ifPresent (w -> System.out.println ("ifPresent->TransformedWorker" + w));
//think about the below statement ...We are using a null worker but it does not throw exception, nice huh ?
nullWorkerOptional.map (w -> {
w.setName ("animal");
return w;
}).ifPresent (w -> System.out.println ("ifPresent->TransformedNULLWorker" + w));
//orElse usage
Worker unWrappedNonNullValueOfOptionalWithOrElse = nullWorkerOptional.orElseGet (() -> getSomeBeanFromSomeWhere ().get ());
System.out.println ("unWrappedNonNullValueOfOptionalWithOrElse = " + unWrappedNonNullValueOfOptionalWithOrElse);
// And converting to the lists
List<Worker> workerList = nullWorkerOptional.map (Collections::singletonList).orElse (Collections.emptyList ());
System.out.println ("Arrays.toString (workerList.toArray ()) = " + Arrays.toString (workerList.toArray ()));
}
private static Worker alternativeWorkerFromSomeWhereElse () {
return new Worker ("Wolverine", 182, 79);
}
public static Optional<Worker> getSomeBeanFromSomeWhere () {
return Optional.of (new Worker ("Logan", 182, 79));
}
public static Optional<Worker> getSomeNullBeanFromSomeWhere () {
Worker nullWorker = null;
return Optional.ofNullable (nullWorker);
}
}
And you can use in streams as follows
Worker w1 = new Worker ("w1", 181, 81);
Worker w2 = new Worker ("w2", 182, 82);
Worker w3 = new Worker ("w3", 183, 83);
Worker w4 = null;
Worker w5 = new Worker ("w5", 185, 85);
List<Optional<Worker>> workerList = new ArrayList<> ();
workerList.add (Optional.ofNullable (w1));
workerList.add (Optional.ofNullable (w2));
workerList.add (Optional.ofNullable (w3));
workerList.add (Optional.ofNullable (w4));
workerList.add (Optional.ofNullable (w5));
List<Optional<Worker>> nonNullList = workerList.stream ().filter (w -> w.isPresent ()).collect (Collectors.toList ());
System.out.println ("Arrays.toString (workerList.toArray ()) = " + Arrays.toString (nonNullList.toArray ()));
view raw streamsOptional hosted with ❤ by GitHub

No comments:

Post a Comment