Sunday, April 7, 2019

Predicates and BiPredicate Functional Interface - JAVA 8


Predicates and BiPredicate Functional Interface


In my previous blog, I’ve already talked about Lambda Expression and Functional Interface. In this blog, I’ll talk about predefined Functional Interface which has been introduced in JAVA 8 under Java.util.Function.

Predicate is a Functional Interface which accept single input and return response in either True or False. It is very similar to Predicates that we have learnt in School i.e. which takes a value and return only Boolean value. The functional method of Predicate is test(Object).

@FunctionalInterface

Public interface Predicate<T>

Here is a simple source code of java.util.function.Predicate
package java.util.function;
    
import java.util.Objects;
    
@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
  }

Where Test (T t) is an abstract method where T is the type of the input to the predicate and will always return a Boolean Value.

Let’s understand this with examples

Example 1:





Example 2:





Example 3:

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateExmaple2 {

       public static void main(String[] args) {

             PredicateExmaple2 predicate = new PredicateExmaple2();

             Predicate<Student> p3 = student -> student.getAge() > 30;
             Predicate<Student> p4 = student -> student.getName().startsWith("A");

             List<Student> students = predicate.populateStudentList();
             for (Student student : students) {
                    if (p3.test(student) && p4.test(student)) {
                           System.out.println("Student Name: " + student.getName());
                           System.out.println("Student Age: " + student.getAge());
                    }
             }
       }

       class Student {
             private String name;
             private int age;

             public Student(String name, int age) {
                    super();
                    this.name = name;
                    this.age = age;
             }

             public String getName() {
                    return name;
             }

             public void setName(String name) {
                    this.name = name;
             }

             public int getAge() {
                    return age;
             }

             public void setAge(int age) {
                    this.age = age;
             }
       }

       public List<Student> populateStudentList() {
             List<Student> studentList = Arrays.asList(new Student("Abdul", 31), new Student("Waheed", 29),
                           new Student("DummyUser", 20));
             return studentList;

       }

}

Output:
Student Name: Abdul
Student Age: 31

Apart from test (T t) method , Predicate also has 3 default method and one static method.


Default Method Name
Explanation
and()
It does logical AND of the predicate on which it is called with another predicate. Example: predicate1.and(predicate2)
or()
It does logical OR of the predicate on which it is called with another predicate. Example: predicate1.or(predicate2)
negate()
It does boolean negation of the predicate on which it is invoked. Example: predicate1.negate()
isEqual()
Compare 2 instances of Predicate functional interface.















Lets understand it with few more example

package com.waheedtechblog.functionalinterface;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateExmaple2 {

       public static void main(String[] args) {

             PredicateExmaple2 predicate = new PredicateExmaple2();

             Predicate<Student> p3 = student -> student.getAge() > 30;
             Predicate<Student> p4 = student -> student.getName().startsWith("A");
             Predicate<Student> p5 = Predicate.isEqual(new PredicateExmaple2().new Student("Abdul", 31));

             List<Student> students = predicate.populateStudentList();
             for (Student student : students) {
                    if (p3.test(student) && p4.test(student)) {
                           System.out.println("Student Name: " + student.getName());
                           System.out.println("Student Age: " + student.getAge());
                    }
             }
             System.out.println("\n");

             System.out.println("=============================");
             System.out.println("=====USING AND PREDICATE======");

             // Using AND PREDICATE
             for (Student student : students) {
                    if (p3.and(p4).test(student)) {
                           System.out.println("Student Name: " + student.getName());
                           System.out.println("Student Age: " + student.getAge());
                    }
             }
             System.out.println("\n");

             System.out.println("=============================");
             System.out.println("=====USING OR PREDICATE======");

             // Using OR PREDICATE
             for (Student student : students) {
                    if (p3.or(p4).test(student)) {
                           System.out.println("Student Name: " + student.getName());
                           System.out.println("Student Age: " + student.getAge());
                    }
             }
             System.out.println("\n");

             System.out.println("=============================");
             System.out.println("=====USING NEGATE PREDICATE======");
             for (Student student : students) {
                    if (p3.negate().test(student)) {
                           System.out.println("Student Name: " + student.getName());
                           System.out.println("Student Age: " + student.getAge());
                    }
             }
             System.out.println("\n");

             System.out.println("=============================");
             System.out.println("=====USING ISEQUAL PREDICATE======");
//Override equals method in Student class
             for (Student student : students) {
                    if (p5.test(student)) {
                           System.out.println("Student Name: " + student.getName());
                           System.out.println("Student Age: " + student.getAge());
                    }
             }

       }

       class Student {
             private String name;
             private int age;

             public Student(String name, int age) {
                    super();
                    this.name = name;
                    this.age = age;
             }

             public String getName() {
                    return name;
             }

             public void setName(String name) {
                    this.name = name;
             }

             public int getAge() {
                    return age;
             }

             public void setAge(int age) {
                    this.age = age;
             }

             public boolean equals(Object obj) {
                    Student student = (Student) obj;
                    if ((this.getName().equals(student.getName()) && this.getAge() == student.getAge())) {
                           return true;
                    } else {
                           return false;
                    }
             }
       }

       public List<Student> populateStudentList() {
             List<Student> studentList = Arrays.asList(new Student("Abdul", 31), new Student("Waheed", 29),
                           new Student("DummyUser", 20), new Student("Adam", 25));
             return studentList;

       }

}

Output:

Student Name: Abdul
Student Age: 31


=============================
=====USING AND PREDICATE======
Student Name: Abdul
Student Age: 31


=============================
=====USING OR PREDICATE======
Student Name: Abdul
Student Age: 31
Student Name: Adam
Student Age: 25


=============================
=====USING NEGATE PREDICATE======
Student Name: Waheed
Student Age: 29
Student Name: DummyUser
Student Age: 20
Student Name: Adam
Student Age: 25


=============================
=====USING ISEQUAL PREDICATE======
Student Name: Abdul
Student Age: 31


BiPredicate Functional Interface


It is very similar to Predicate Functional Interface. The only difference is just that it will accept two argument instead of one and as usual will return the Boolean Value.

@FunctionalInterface
public interface BiPredicate<T,U>


Let’s see how can we achieve Example 4 using BiPredicate Interface

import java.util.Arrays;
import java.util.List;
import java.util.function.BiPredicate;

public class BiPredicateExample {

       public static void main(String[] args) {

             BiPredicateExample predicate = new BiPredicateExample();

             BiPredicate<Integer, String> b1 = (age, name) -> age > 30 && name.startsWith("A");

             List<Student> students = predicate.populateStudentList();
             for (Student student : students) {
                    if (b1.test(student.getAge(), student.getName())) {
                           System.out.println("Student Name: " + student.getName());
                           System.out.println("Student Age: " + student.getAge());
                    }
             }
       }

       class Student {
             private String name;
             private int age;

             public Student(String name, int age) {
                    super();
                    this.name = name;
                    this.age = age;
             }

             public String getName() {
                    return name;
             }

             public void setName(String name) {
                    this.name = name;
             }

             public int getAge() {
                    return age;
             }

             public void setAge(int age) {
                    this.age = age;
             }

             public boolean equals(Object obj) {
                    Student student = (Student) obj;
                    if ((this.getName().equals(student.getName()) && this.getAge() == student.getAge())) {
                           return true;
                    } else {
                           return false;
                    }
             }
       }

       public List<Student> populateStudentList() {
             List<Student> studentList = Arrays.asList(new Student("Abdul", 31), new Student("Waheed", 29),
                           new Student("DummyUser", 20), new Student("Adam", 25));
             return studentList;

       }

}

Output:

Student Name: Abdul
Student Age: 31
  

That’s it for Predicate and BiPredicate Functional Interface, Will talk about other Predefined Functional Interface in my next blog.


Happy Coding…!!!





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…!!!




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...