Sunday, April 26, 2015

Java 8 Functional interfaces- Function, Consumer, Supplier and Predicate

Expressions are so confusing

Java 8 release has included many functional interfaces in package java.util.function.
These interfaces are heavily used all over the places. Optional and collection Stream API to name a few.
When I started using lambda expressions, I tried to remember the usage and pattren of expression expected in specific method. For example, stream().forEach expects expression with one parameter and void expression while Optional.filter method exptects single parameter and boolean expression. So I realized that I need to understand the usage instead of remembering the pattern.



Understanding common functional interfaces

Function interface:

Function interface has following method
R apply(T t);
From the method declaration we can guess that it expects one type of object and returns different type of object. As the name suggests, this interface represents a function which accepts an argument and produces result.
Lets observe some usages of this interface.
Stream -> <R> map(Function<? super T, ? extends R> mapper)
From the these details we can say that when we call map method, we need to write a expression, which will get a single parameter and it should return an object. The type of parameter and returned object could be different.


Consumer Interface:

Consumer interface has following method.
void accept(T t);
Like any other kind of Consumer, this method cosumes a object and doesnt return anything.
Lets observe some usages of this interface.


Optional -> void ifPresent(Consumer<? super T> consumer)
This method take a parameter and its expected that expression should any necessory action based on input.
ifPresent method checks if value is present in optional. If value is not present then it doesn't do anything being a void method. If value is present then executes the expression, passed to the method.


 Stream -> void forEach(Consumer<? super T> action); 
In this example, the stream object executes the provided expression, for the each object in the stream.


Supplier Interface:

Suplier provides or suplies the information/object.
It has very simple method.
T get();
This method expects no paramer and should have a expression which returns a object.

Lets observe its usage.
Optional ->  T orElseGet(Supplier<? extends T> other)
orElseGet method returns the value if present or calls the expression provided which in tern, returns a object.


Predicate interface:

Predicate is  one of the most widely used funcational Interface.
The dictionary meaning of predicate is as follows.
something which is affirmed or denied concerning an argument of a proposition.
So basically its a test which returns true or false.

Predicate Interface has following method.
boolean test(T t);
From method signature, we can say, it expects a parameter and a expression which is boolean in nature.

Lets observe some examples.
Stream -> <T> filter(Predicate<? super T> predicate);
Filter method is used to filter the objects provided in the collection, based on the test provided in expression.


My aim is not to explain about these functional interface, but provide you a vision so that you should be able to deal with any new functional Interface you come across.
I hope this will help you writting your next lamda expression. 

Saturday, April 25, 2015

Java 8- Optional

What is Optional in java 8?
Java 8 have added a class java.util.Optional to solve some of the problems associated with handling or manipulating the objects.
Its a container object which may or may not contain a non-null value.
Optional can hold a null or object. It allows to replace "!= null" or "== null" to more readable isPresent().It helps to map object to a different object or assign some defaults if original one is not present.

Why optional? Can't we achieve it with existing things?
Java started its journey by leaving behind the concept of pointer. In the course it got the curse of NullPointerException. Its not possible to find a java developer not fustrated with NPE. Optional provides one more wrapper over object. Proper use of Optional can free you from NPE.
Major part of java code is written to to check if object is null or not, then retrieve another object from it or manipulate its values. Optional makes these things easier and readable.

Enough, show me some code.
  • Optional can be created in three different ways.
  1. Optional<T> empty() : Provides optional object which doesn't has any value. It demostrates Null Object pattern
  2. Optional<T>of(T value): Should be used when you are sure that the object for which optional is created is not null. Example - Optional.of(new Student(23)); Throws NullPointerException if null is passed to the method.
  3. Optional<T> ofNullable: Should be used when you are not sure if value is null or not.
All 3 methods are static.

  • Getting rid of != null check
Optional<String> name = someMethodWhichGivesMeString();
if(name.isPresent()){
    System.out.println(name.get());
}
public Optional<String> someMethodWhichGivesMeString(){
return Optional.of("Sumit");
}
  • Making use of lambda expressions
Optional<String> name = someMethodWhichGivesMeString();
name.ifPresent(n -> System.out.println(n));

  • Mapping MangoDomain to MangoBean
Optional<Mango> mango = getMango();
// Inline mapping
Optional<MangoBean> mangoBean = mango.map(m -> new MangoBean(m.getColor()));
//Mapping extracted in separate method  
Optional<MangoBean> mangoBean2 = mango.map(Mango:: getMangoBean());

  • Mapping MangoDomain to MangoBean when mapper returns optional
map and flatMap are similar methods. The difference is the argument. flatMap method expects method which returns Optional.
Optional<Mango> mango = getMango();
MangoBean mangoBean = mango.flatMap(Mango:: getMangoBean());


  • Discard that rotten mango
Sometime, we have to filter object based on some logic.

  •  Optional<Mango> mango = mango.filter(m -> "GREEN".equals(m.getColor()) || "YELLOW".equals(m.getColor()));
If mango is green or yellow, then you will get it or it will be an empty optional object.


  •  Defaults...
While doing operations like map, filter etc, if the optional is empty then we can configure some default operations

  • mango.orElse(other)
It will return the value (mango) if present otherwise other of type Mango.
 mango.orElse(new Mango());


  • mango.orElseGet(supplier)
It will return the value (mango) if present otherwise return type Mango by invoking supplier.
mango.orElseGet(()->new Mango()); 


  • orElseThrow(Supplier<? extends X> exceptionSupplier)
It returns the mango value if present otherwise throws exception by invoking supplier.
mango.orElseThrow(()->new RuntimeException());    

Clubing everyting together

//Old way
        Mango mango = new Mango(YELLOW);
        Fruit fruit1;
        if(mango !=null &&
                YELLOW.equals(mango.getColor())){
            fruit1 = new Fruit(mango.getColor());
        }else{
            fruit1 = new Fruit(GREEN);
        }
   
//With Optional
        Optional<Mango> mangoOptional = Optional.of(new Mango(YELLOW));
        Fruit fruit = mangoOptional
                .filter(m -> YELLOW.equals(m.getColor()))//Filter Yellow mango
                .map(m -> new Fruit(m.getColor()))//Map it tp fruit
                .orElseGet(() -> new Fruit(GREEN));//if mango is not yellow or there is no mango at all create default fruit

Sources:
http://blog.jhades.org/java-8-how-to-use-optional/
http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
http://www.concretepage.com/java/jdk-8/java-8-optional-example-avoid-nullpointerexception

Friday, April 24, 2015

Some cool and useful SQL queries

There are some queries I came across many time while interacting with database. I have compiled some of those. I have tested these queries on Oracle 11g database. I hope it will help you too.

Note: If you want to create table structure and populate with the data used in these examples, then you can use the sql file from here.

  • Record Ranking

Record ranking is as its name suggests provides rank to the records fetched. Till now I came across 3 approaches.
Row Number- Provides natural numbers to each row. It could be called as Ordinal ranking in laymans term
SELECT
  ROW_NUMBER() OVER (ORDER BY sal DESC) salary_rank,
  empno,
  ename
FROM emp;




Rank - Honors same rank to all the records with same value but follows Standerd competition ranking
SELECT
  RANK() OVER (ORDER BY sal DESC) salary_rank,  empno,sal,enameFROM emp;


Dense Rank - Follows Dense ranking system
SELECT  DENSE_RANK() OVER (ORDER BY sal DESC) salary_rank,  empno,sal,enameFROM emp;

  • Top n analysis: 
In many cases its required to know first few records based on some criteria, like first 5 employees with highest salery, or most experienced 10 employees. Top n analysis is handy in such cases.

SELECT ROWNUM,  ENAME, EMPNO, SAL FROM   (SELECT *    FROM EMP    ORDER BY SAL DESC) E1 WHERE rownum<4;
This query provides top 3 employees with highest salary.


  • Nth record

Similar to top n analysis, this query provides employee with perticular ranking.
Following query return employee with 3rd highest salary
select * from (select row_number() over (order by sal desc) salary_rank, emp.* from emp) where salary_rank=3;

  • Top Nth item per group

This is special case of nth record query. Of the example could be employees with third highest salary in each department.
WITH temp_emp AS   ( SELECT empno,deptno
           ename,            row_number() over (partition BY deptno                               ORDER BY sal DESC) AS rownm    FROM emp ) SELECT * FROM temp_emp WHERE rownm =3;

  • Hierarchical/Recursive Query

This one is  my favourite. It shows power of sql.
This approach is useful when your table contains hierarchical data.
Take an example of our favourite employee table. This table contains employee and his manager. Manager himself is employee and could report to his manager. This hierarchy goes on till CEO of the company.
If you have a requirement where you need to show all the employees falling under hierachy of employee 7566 then following query can do the trick.

WITH VIR_EMP(EMPNO,MGR) AS   ( SELECT EMPNO,MGR    FROM EMP    WHERE MGR=7566    UNION ALL SELECT TEMP_EMP.EMPNO,TEMP_EMP.MGR    FROM EMP TEMP_EMP,VIR_EMP    WHERE TEMP_EMP.MGR=VIR_EMP.EMPNO ) SELECT EMPNO,        MGR FROM VIR_EMP;

  • No of records with same data/ duplicate records with count

SELECT emp1.empno,        emp1.sal,        cnt FROM emp emp1 INNER JOIN   (SELECT sal,           count(sal) cnt    FROM emp    GROUP BY sal) emp2 ON emp1.sal=emp2.sal;

  • Remove Duplicate records but leave one

This one could be really useful for cleaning up the duplicate records.
DELETE FROM emp WHERE empno NOT IN     (SELECT MIN (empno)      FROM emp      GROUP BY deptno);