Tuesday, February 12, 2019

Java 8: Sorting of Collection using lambda Expression


In my previous blog, I have already discussed on Lambda Expression and its Syntax as well as Functional Interface. So, if you are not aware of then I would suggest you to read those blogs before starting this one.


As we know Comparator Interface is also a Functional Interface as it has only one abstract method. In this blog, we will see how we can do sorting using lambda expression.

Let’s start with List and will cover Set, Map as well as Custom Class as well.

  1. List

Sorting of elements on any Array List can be done easily using Collections.sort(…) functions where sort() can take argument as list or with list, you can also pass comparator object.

In below example, we will see how can we sort using comparator and the same task with lambda expression.



Output:

2  2.   Set

Output:


    3. Map

Output:

4. Sorting on custom class with Lambda Expression

/**
 *
 */
package com.waheedtechblog.collection;
import java.util.ArrayList;
import java.util.Collections;
/**
 * Custom class sorting using lambda expression.
 *
 * @author Abdul Waheed
 *
 */
class Book {
private int bookId;
private String bookName;
public Book(int bookId, String bookName) {
this.bookId = bookId;
this.bookName = bookName;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + "]";
}
}
public class CustomClassSorting {
public static void main(String[] args) {
Book book1 = new Book(205, "Java");
Book book2 = new Book(300, "Python");
Book book3 = new Book(300, "Spring framework");
Book book4 = new Book(503, "Hibernate");
ArrayList<Book> books = new ArrayList<Book>();
books.add(book1);
books.add(book2);
books.add(book3);
books.add(book4);
System.out.println("Book object natural Sorting\n" + books);
Collections.sort(books,
(b1, b2) -> (b1.getBookId() > b2.getBookId()) ? -1 : (b1.getBookId() < b2.getBookId()) ? 1 : 0);
System.out.println("Book object after Sorting in DESC order\n" + books);
}
}

Output:
Book object natural Sorting
[Book [bookId=205, bookName=Java], Book [bookId=300, bookName=Python], Book [bookId=300, bookName=Spring framework], Book [bookId=503, bookName=Hibernate]]

Book object after Sorting in DESC order
[Book [bookId=503, bookName=Hibernate], Book [bookId=300, bookName=Python], Book [bookId=300, bookName=Spring framework], Book [bookId=205, bookName=Java]]

You can download the source code from Github

Happy Coding...!!!







Sunday, February 10, 2019

Don't clear logs after app get crashed - Android Studio

Currently, I am working on one app which keep getting crash at PIE version and I was not getting any crash log under logcat.

After some research here and there, I get to know that by default logcat logs based on selected process and once your app get crashes, it will clear the crash log as the existing process is gone.

To see the crash logs:
·        Goto logcat and click on right hand side drop down button and select Edit Configuration.


·        Add Filter Name as your app Name and project Name as Package Name. Save it.


Now try again. You will able to see your app crash log now. 

Thank you. Happy Coding…!!!




Tuesday, January 22, 2019

Functional Interface and Lambda Expression




Functional Interface and Lambda Expression



Functional Interfaces

A functional interface is an interface that contains only one abstract method. It can have one or more default or static method but abstract method should be only one.

Runnable, Callable, ActionListener, Comparable are some of the examples of functional interfaces as it contains only one abstract method.

Let’s see some functional Interface implementation example:
Example 1:

public interface SimpleInterface {
    public void abstractMethod();
}
It’s a functional Interface as it only contains a single abstract method.

Example 2:
public interface ComplexInterface {
    public void abstractMethod();
    public default void defaultMethod(){
        System.out.println(“Default method”);
    }
    public static void staticMethod(){
        System.out.println(“Static method”);
    }
}
Above example #2 is also a valid functional interface as it only contains one abstract method and rest are either default or static method.

Example 3:
public interface ComplexInterface {
    public void abstractMethod();
    public void anotherAbstractMethod();
    public default void defaultMethod(){
        System.out.println(“Default method”);
    }
    public static void staticMethod(){
        System.out.println(“Static method”);
    }
}
The above example #3 is not a valid functional Interface as it contains more than one abstract method.

#1 and #2 are valid Functional Interface but #3 is not. For lambda expression, An interface must be a functional interface else you will end up in error. So, How can we force compiler to check whether the Interface is functional or not and if not then it should give compiler time error?

@FunctionalInterface Annotation
It is used to ensure that the functional interface can’t have more than one abstract method. If you add more or less abstract method then compiler will show compile time error message.

Note: An interface with one abstract method will be called as Functional Interface whether you add the @FunctionalInterface annotation or not but it is always a good practise to add annotation as it will avoid addition of extra method accidentally.

Lambda Expression

Lambda expressions is used to represent the instance of a functional interface i.e. using Functional Interface reference we are allowed to call lambda expression implementation.
If you don’t know what is lambda expression or how to write lambda expression then you can read my blog on lambda expression over here.

Let’s try to understand the above definition with few examples:


Example 4:
I am just using the example#1 over here

public interface SimpleInterface {
    public void abstractMethod();
}

Before Java 8, Either we had to create anonymous inner class or we had to implements interface to implement the function method.

class BulkyClass implements SimpleInterface {
    @Override
    public void abstractMethod(){
        System.out.println(“Abstract Method Implementation”);
    }
}

To invoke method:
class Test {
    public static void main(String[] args){
        SimpleInterface si = new BulkyClass();
        si. AbstractMethod(); // Will display message on Console.
    }
}

Now, let’s see how Functional interface can be implemented by a Lambda Expression.

Over here, We don’t need any more BulkyClasses. We can just directly call it
class Java8 {
    public static void main(String[] args){
        SimpleInterface si = () -> System.out.println(“Abstract Method             Implementation”);
        si.abstractMethod(); // Will display message on Console.
    }
}

If you observed it carefully, We’ve invoked the lambda expression implementation using Functional Interface.
Let’s see another famous Functional Interface i.e. Runnable Interface. Runnable interface contain only one method which is run and the return type is void
Similarly, We can write anonymous Runnable using Lambda
Expression.

public ThreadExampleWithJava8 {
    p.s.v.m() {
        Runnable r = () -> {//stattement1
            statement2;
        }
        Thread th = new thread(r);
        th.start();
    }
}
  • As Runnable is a functional interface, that’s why we can use lambda expression to create it’s instance.
  • Since run() method takes no argument, our lambda expression also have no argument.
  • Just like if-else blocks, we can avoid curly braces ({}) since we have a single statement in the method body. For multiple statements, we would have to use curly braces like any other methods.

Why do we need Lambda Expression

  1. Reduced Lines of Code

  2. Sequential and Parallel Execution Support

  3. Passing Behaviours into methods

Will explain the above point with example in my next blog. Over here, Let’s just focus on Functional Interface and example.

Example 5:

@FunctionalInterface
public interface firstInterface {
     public void method1();
}
@FunctionalInterface
public interface secondInterface extends firstInterface{
}
if an interface extends functional Inference and child interface does not contains any abstract method then child interfaces will also be a valid functional interface.

Example 6:
@FunctionalInterface
public interface firstInterface {
    public void method1();
}
@FunctionalInterface
public interface secondInterface extends firstInterface{
    public void method1();
}
If base and super interface contains one abstract method and both method are same then secondInterface will also be a valid Functional Interface. Why? Because of Overriding property., second Interface will have only one abstract method.

Example 7:
@FunctionalInterface
public interface firstInterface {
    public void method1();
}
@FunctionalInterface
public interface secondInterface extends firstInterface{
    public void method2();
}
Over here, Second Interface will throw compile time error as it will be having two method i.e. method2 as will as method1 from firstInterface.

Example 8:

@FunctionalInterface
public interface firstInterface {
    public void method1();
}
public interface secondInterface extends firstInterface{
    public void method2();
}

Over here, Though Second Interface is not a Functional Interface still it will not throw any compile time error as it doesn’t have @FunctionalInterface annotation.

Saturday, January 5, 2019

How to write Lambda Expression in Java 8


   How to write Lambda Expression?



With the introduction of Lambda Expression in JAVA 8, We can write more readable, maintainable and concise code but I have seen people keep forgetting the syntax of lambda expression or they are always confused with it.

In this blog, I ll just try to explain the basic things i.e. how easy is it to write Lambda Expression but before starting with the syntax, Let’ see what is lambda Expression?

In simple term, Lambda expression (->) is an anonymous function which
    - doesn’t have any name
    - doesn’t have any modifiers
    - doesn’t have any return type.

To understand it in a more easy way, Let’s first write a simple Java function which display some message on the console.

Example 1: Display Message

  1. public void display (){ 
  2.     system.out.println(“Learning Lambda Expression”); 
Now to convert the above code into lambda expression, read the lambda definition once again i.e. it says no modifiers, no return type and no function name.

Step 1: Delete public (Modifier) void (return type) and display ( function name) from first line.

  1. public void display (){ 
  2. system.out.println(“Learning Lambda Expression”); 

Step 2: Add Lambda Expression Symbol before curly braces.

           () -> {system.out.println(“Learning Lambda Expression”);}

That’s it, We have converted the normal Java code into Lambda Expression form. Just delete the name, return type, modifier and add lambda expression symbol and you are done :)


Code Optimization: The above syntax is correct but we can optimize it further...

Rule 1: if the function body has only statement then we can remove the curly braces.

             () -> system.out.println(“Learning Lambda Expression”);


Example 2: Addition of two numbers

  1. public void sum(int x, int y) { 
  2.     system.out.println(x+y); 
The lambda expression for #2 after removing modifier, name, return type and after applying Rule#1 will be

             (int x, int y) -> system.out.println(x+y);

Isn’t it simple? Right?

Let's see the second rule


Rule 2: Use Parameter type Inference. If you don’t know what is Type Inference then you can read my blog over here. In one line, Type Inference is the ability of the compiler to look at the method and to guess the correct method invocation. So we can remove int type from method parameters.

           (x, y) -> system.out.println(x+y); 


Example 3: Returns the length of String

  1. public int getLength(String s){ 
  2.     return s.length(); 
The lambda expression for #3 after removing modifier, name, return type and after applying Rule#1 & Rule#2 will be

           (s) -> return s.length();

Rule 3: Again as per Type Inference, We can also ignore the return type over here as compiler can guess easily the return type.

             (s) -> s.length();

Rule 4: if the function has single parameter then we can ignore it. So the final optimize and concise Lambda expression for Example 3 would be

               s -> s.length();

That's it  for now. Will try to cover other topics of JAVA 8 in my next blog.

Happy Coding...!!!

Java 8 - Type Inference


Java 8 – Type Inference

Type inference was first introduced in JDK 7 and later improved in JDK 8. It is a feature of Java which provides ability to compiler to look at each method invocation and corresponding declaration to determine the type of argument(s).

The inference algorithm checks the types of the arguments and,if available, assigned type is returned. It tries to find a specific type which can full fill all type parameters.

Till Java 6, We have to declare an Arraylist by mentioning its type explicitly at both side.
            List<Integer> numbers = new ArrayList<Integer>();
and if we keep the type as blank at right side then Compiler generates unchecked conversion.
            List<Integer> numbers = new ArrayList<>();

With JDK 7, It got improved and we started mentioning the type of arraylist only at one side. Below we can left second side as blank diamond and compiler will infer type of it by type of reference variable. Now, compiler will not generate any warning
            List<Integer> numbers = new ArrayList<>();

Improved Type Inference in JDK 8
Now, we can call specialized method without explicitly mentioning of type of arguments.
            sum(new ArrayList<>());

Let’s see the java implementation




How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...