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

Thursday, February 9, 2017

Java 8 Lambda Building Blocks: Predicate, Function, Consumer, Supplier, BinaryOperator

















Let the code explain itself..Be quiet...And read..







Predicate<T>-- T in ,boolean out
Predicate<Man> richManMatcher = m->m.getCashAmount () > 1000000;
if (richManMatcher.test (someMan)) {
marryWithRichMan (someMan);
}
Function<T,R> -- Tin, R out
Function<Worker,Integer> salaryIncreaser = w->w.getSalary () + 500;
for (Worker worker: workers){
worker.setSalary (salaryIncreaser.apply(worker));
}
// OR with Method References
workers.stream ().map (salaryIncreaser::apply);
BiFunction<T,U,R> -- Tin, R out
Worker worker = new Worker ("worker",120,80);
List<Worker> workers = new ArrayList<> ();
BiFunction<Integer, Integer, Integer> bodyIndexCalculator = (h,w) -> h/w;
Integer workerBodyIndex = bodyIndexCalculator.apply (worker.getHeight (), worker.getWeight ());
workers.stream ().mapToInt (w->bodyIndexCalculator.apply (w.getHeight (),w.getWeight ())).average ();
Consumer<T> --T in, void
Consumer<Worker> salaryIncreaser = w->w.setSalary (w.getSalary () * 1.2);
for (Worker worker: workers){
salaryIncreaser.accept(worker));
}
Supplier<T> -- Nothing In -- T out
Supplier<Worker> hardWorkingWorkerSupplier = ()->randomWorkerFromSomeWhere();
Worker w = hardWorkingWorkerSupplier.get();
BinaryOperator<T> -- TwoT's in, T out
BinaryOperator<Integer> multiplier = (n1,n2) ->n1 * n2;
int multipliedvalue = multiplier.apply (n1,n2);



Bye


Java 8 Lambda Expressions

I'll try to explain the topic according to my motto --"No bullshit , Just Code.."

1) SAM= Single Abstract Method = An Interface with Only One Method = Functional Interface

@FunctionalInterface
public interface StateChangeListener {
public String onStateChange(State oldState, State newState);
}
view raw sam hosted with ❤ by GitHub
2) A class with a method which will consume a lambda expression

public class StateManager {
public void addNewStateListener(StateChangeListener listener) { //blahh }
}
view raw LamdbaConsumer hosted with ❤ by GitHub
3) Now.. Actionnn...Lambda expression as a parameter

StateManager stateManager = new StateManager();
stateManager.addNewStateListener(
(oldState, newState) -> System.out.println("State changed")
);




Okeyy... I know some of you need bullshit also :)

If you want to pass a behavior to a parameter (behavior= function=action) just create an interface and annotate it @FunctionalInterface and use Lambda Syntax like i did in above.

(param1,param2,,,,,paramN) -> {play with params}

Java 8 lots of built in @FunctionalInterface inside it. You can use them anywhere you need. Just  google for them .

Bye

Wednesday, February 8, 2017

Adapter Pattern VS Decorator Patter VS Facade Pattern VS Proxy Pattern VS Bridge Pattern - Summary - Table

I know this is not very presentable but it is easier to remember design patterns in the below format (at least for me).
Whatever...
Above is a list of Structural Design Patterns.
All of them is encapsulates some objects or interfaces and delegates the calls to them at the bottom . 
So what is difference between them on top of their behaviour ?
The difference is your intent !

And I don't recommend you to memorize them .Just read them once and hope to get an inspiration when you needed those.

Just encapsulate and delegate. --From "The Joy of Painting"