Functional interface in java8.

            Interface is the one which has only abstract methods. It has only declaration. It implements the concept of abstraction. Functional interfaces are important concept in java 8.

What is functional interface??

              Functional interface has only one abstract method. This uses lambda expressions to implement the method.

Built in package: java.util.function

Common functional interfaces:

The below functional interfaces are commonly used from java SE1.8 onwards.

  • ActionListener, Runnable, Callable, Comparable.

Simple program to implement functional interface using Runnable:

class Test {

    public static void main(String args[])

    {

      Runnable runnable = () -> System.out.println("A threat is running separately");

      new Thread(runnable).start();

    }

}

Java 8 Functional interfaces:

              These are the functional interfaces are included in java8 for performing in multiple situations.

  1. Consumer
  2. Predicate
  3. Function 
  4. Supplier
  5. Consumer -> Bi-Consumer
  6. Predicate -> Bi-Predicate
  7. Function -> Bi-Function, Unary Operator, Binary Operator 

Java Program for implementing functional interface for Book information System:

·       Create a book class with four elements. Id, Name, price and Description.

·       Using constructors, initialise the values.

·       Create the object for Book class and add the value.

class Book

{

    int id;

    String name;

    double price;

     String specialization;

     public Book(int id, String name, double percentage, String specialization)

    {

        this.id = id;

        this.name = name;

         this.price = price;

        this.specialization = specialization;

    }

     public int getId() {

        return id;

    }

     public String getName() {

        return name;

    }

     public double getPrice() {

        return price;

    }

     public String getSpecialization() {

        return specialization;

    }

     @Override

    public String toString()

    {

        return id+"-"+name+"-"+price+"-"+specialization;

    }

}

 

List<Book> listOfBooks = new ArrayList<Book>();

listOfBooks.add(new Book(11, "Let us C",250.15 , "computer Science"));

listOfBooks.add(new Book(11, "Let us C++",315 , "computer Science"));

listOfBooks.add(new Book(11, "Learn Java Programming ",475 , "computer Science"));

listOfBooks.add(new Book(11, "Python programming",370 , "computer Science"));

listOfBooks.add(new Book(11, "SQL Programmimg",276 , "computer Science"));

 

How to use functional interfaces for this class “Book”:

1.Predicate:

This functional interface  used to Check a specific book.

For example,

Predicate <Book> Programming = (Book book)-> book.getSpecialization.equals(“Java Programming”);

List<Book> Programming = new ArrayList<Book>();

for (Book book : listOfBooks)

{

    if (Programming.test(book))

    {

        Programming.test(book);

    }

}

 

2. Consumer :

              Using this functional interface,we display the prices of all books.

Consumer<Book> PriceList = (Book book) -> {

        System.out.println(book.getName()+" : "+book.getPrice());

    };

         

for (Book book : listOfBook)

{

    price.accept(book);

}

3. Function:

              This functional interface extracts the book name alone from the system.

Function<Book, String> bookNameFunction = (Book book) -> Book.getName();

List<String> BookNames = new ArrayList<String>();         

for (Book book : listOfBooks)

{

    bookNames.add(bookNameFunction.apply(book));

}

4. Supplier :

 This is used to  Create a new book information.

Supplier<Book>  bookSupplier = () -> new Book(666, "Perl Programming", 921.45, "Computer Programming");

listOfBooks.add(bookSupplier.get());

These are the ways to use functional interfaces in java 8.

how to use Lambda expressions in java?

               Java 8 has an important functionality called lambda expressions. It involves functional interfaces. Functional interfaces are the one which has single abstract method.

Syntax of the lambda expression is given below.

(parameters) -> body

Where

Parameters – It holds the input value.

è -> - It is the one which separates the parameters and body.

Body – It is the code to be executed.

Eg:

The parameters may be single or multiple in number.

(a)-> a+a

(a,b)-> a-b

(a,b,c)-> a+b+c

How to use lambda expressions???

              Generally, Lambda expressions are used to pass arguments to functions. It can be stored as variables or method parameters. But the type should be an interface of single method.

Java Program to use lambda expressions:

  • è In the beginning, create an interface SumInterface. It is a functional interface which has single method “add”. “add” method has two integer parameters.
  • è Next, create a public class “SumLambdaExample” which has the main method. So, save this program as “SumLambdaExample.java”.
  • è Furthermore, create an object for interface addition. Create a lambda expression for addition of two numbers and store it to addition (interface object).
  • è Finally, print the sum value by calling the function sum with two parameters.

   interface SumInterface {

       int add(int a, int b);

   }

   public class SumLambdaExample {

       public static void main(String[] args) {

           SumInterface addition = (a, b) -> a + b;

           System.out.println("Sum of the two numbers are: " + addition.add(65, 43));

       }

   }

While running this program, the user will get this output.

In the same way, you can use the lambda expressions for other arithmetic operations also.

Here are the sample codes.

Replace the first code by others for your program.

   interface SumInterface

   interface SubInterface

   interface mulInterface

   interface divInterface

int add(int a, int b);

int sub(int a, int b);

int mul(int a, int b);

int div(int a, int b);

           SumInterface addition =

 (a, b) -> a + b;

 

           SubInterface subtraction=

(a, b) -> a - b;

 

           mulInterface

multi  = (a, b) -> a * b;

 

           divInterface division = (a, b) -> a / b;

 

addition.add(65, 43))

subtraction.sub(65, 43))

multi.mul(15, 14))

division.div(45, 9))

 These are the ways to use lambda expressions in java programs.

How to write a java program to print pattern:

     Pattern is an arrangement of elements.  It may be a mathematical shape like square, rectangle, triangle.  These shapes may be printed as hollow pattern, solid pattern or number pattern.

In this blog post, we create three different patterns.

  1.   Solid Square Pattern
  2.   Hollow Rectangle pattern
  3.   Number Triangle pattern

 1.How to print Solid Square pattern in java:

  • ·       This java program uses “#” pattern to print solid square. For printing this pattern, a function “printIt()” is written.
  • ·       This function has two for loops. One for row and another one for column value. Based on the loops, it prints the pattern.
  • ·       In the main function, row and column value is assigned and the printIt() is called using the row and column value.

#Java Program to print Solid square pattern

 public class SquarePattern {

    public static void printIt(int row, int cols) {

        for (int i = 0; i < row; i++) {

            for (int j = 0; j < cols; j++) {

                System.out.print("# ");

            }

            System.out.println();

        }

    }

  public static void main(String[] args) {

        int row = 4;

        int cols = 4;

        printIt(row, cols);

    }

}

·       The output is shown below.


 2.How to print hollow rectangle pattern in java:

  • ·       This java program uses “@” pattern to print solid Rectangle. Here,function “printHollow()” holds the code to print the pattern.
  • ·       It uses two for loop to print the pattern.
  • ·       In the main function, row and column value is assigned and the printHollow() is called using the row and column value.

#Java Program to print rectangular hollow pattern

public class RectPattern {

    public static void printHollow(int row, int col) {

        for (int I = 0; I < row; i++) {

            for (int j = 0; j < col; j++) {

                if (I == 0 || I == row- 1 || j == 0 || j == col – 1)

                {

                    System.out.print(“@ “);

                }

                else {

                    System.out.print(“  “);

                }

            }

            System.out.println();

        }

      }

   public static void main(String[] args) {

        int row = 6;

        int col = 4;

        printHollow(row, col);

    }

}

·       This program gives you the output as shown below command prompt.

3.How to print Number Triangle pattern in java:

·       This program prints numbers in triangular pattern.Here, printNumber() is used to print the numbers.

·       It gets the values from main() function.

#Java Program to print Triangle number pattern

public class TriaPattern {

    public static void printNumber(int n) {

        for (int i = 1; i <= n; i++) {

            for (int j = 1; j <= n - i; j++) {

                System.out.print(" ");

            }

            for (int j = 1; j <= i; j++) {

                System.out.print(i + " ");

            }

            System.out.println();

        }

    }

 

    public static void main(String[] args) {

        int n = 6;

        printNumber(n);

    }

}

·       Compile and run the program. The output is displayed here.

These are the ways of creating java programs to print the various patterns. Happy coding!!!!!

Java program to implement in order traversal in binary tree:

              Binary tree is a data structure which stores data in tree structure. It has a root with two child(Left and right child). Root is a parent element.

In order Traversal:

              It follows a simple pattern for traversal (Left -Root -Right).  In the beginning, traverse a left sub tree followed by root node. Finally, Right sub tree is traversed.

Java program to implement in order traversal in binary tree:

  • ·       First, create a binary tree. It needs a node to be defined. So, create a class “node” with three elements(Left and right nodes and key).
  • ·       Next, create a member function Node. Assign the value to key. Left and right values as null.
  • ·       Develop a BinaryTree class. Create a object for Node. Initialise the constructor.
  • ·       A method insert(key)  is created to insert the values to a newnode in binary tree.
  • ·       Next method is insertRec() with root and key. It inserts the key in proper position. Either left or right child of node.
  • ·       There are two methods to implement inorder traversal (inorder(), inorderRec()). These are used to perform in order traversal.
  • ·       Now, in the main(), a new object is created for BinaryTree class. Insert values to the node by insert() function.
  • ·       Call the inorder member function and perform the inorder traversal.
  • ·       Finally, print the tree values.

//Creating  a class node

class node {

    int key;

    node left, right;

    public node(int value) {

        key = value;

        left = right = null;

    }

}

//Creating a class BinaryTree

public class BinaryTree {

    node root;

    public BinaryTree() {

        root = null;

    }

 

    // Insert the key value to root node.

    public void insert(int key) {

        root = insertRec(root, key);

    }

 

    // Insert other key values to node using a recursive function

    private node insertRec(node root, int key) {

        if (root == null) {

            root = new node(key);

            return root;

        }

        if (key < root.key) {

            root.left = insertRec(root.left, key);

        } else if (key > root.key) {

            root.right = insertRec(root.right, key);

        }

        return root;

    }

 

    // Inorder traversal function

    public void inorder() {

        inorderRec(root);

    }

 

    // supportive function for inorder traversal

    private void inorderRec(Node root) {

        if (root != null) {

            inorderRec(root.left);

            System.out.print(root.key + " ");

            inorderRec(root.right);

        }

    }

 

    public static void main(String[] args) {

        BinaryTree tree1 = new BinaryTree();

 

        // Insert values to binary tree

        tree1.insert(78);

        tree1.insert(39);

        tree1.insert(55);

        tree1.insert(20);

        tree1.insert(87);

        tree1.insert(125);

        tree1.insert(60);

 

        // display the values of inorder traversal

        System.out.println("Inorder traversal:");

        tree1.inorder();

    }

}

You will get this output when you execute this program.

This is the way of implementing  a java program to perform inorder traversal of binary tree.

Java program to calculate the execution time of methods:

     Execution is the final part in coding. It loads and links the object code into memory. While executing a code, it is important to measure the execution time. There are many methods to measure the execution time

        1.  Using nanoTime()

        2.   Using currentTimeMillis()

        3.   Using Instant and Duration

1.Using nanoTime():

              Here, we use nanoTime() built in method. This program gets two inputs as starting time and ending time using System.nanoTime(). Find the difference and store it in a variable. Print the variable.

public class nano {

    public static void main(String[] args) {

        // Reads the system time. let it be the starting time.

        long sTime = System.nanoTime();

        SimpleMeasure();

        // Gets the ending time

        long eTime = System.nanoTime();

        // find the execution time by finding different between staring and ending time

        long duration = (eTime - sTime); // in nanoseconds

        System.out.println("Execution time is: " + duration + " nanoseconds");

    }

       public static void SimpleMeasure(){

        // Example method to measure

        for (int i = 0; i < 1000000; i++) {

            // sample measure

        }

    }

}

Compile and run the program. You will get the below output.

2.Using System.currentTimeMillis():

              This method uses built in function currentTimeMillis(). This program reads two time for measuring the execution time.

Here, is the program.

public class Measure {

    public static void main(String[] args) {

        // Gets the starting time

        long sTime = System.currentTimeMillis();

        // Simple method to measure

        SimpleMeasure();

        // Gets the end time

        long eTime = System.currentTimeMillis();

        // find the execution time

        long duration = (eTime - sTime); // in milliseconds

        System.out.println("Execution time is: " + duration + " milliseconds");

    }

    public static void SimpleMeasure() {

        // simple method to measure

        for (int i = 0; i < 1000000; i++) {

            // simple process

        }

    }

}

When executing this program, you will get the output.

Ø  Execution time is: 453534 milliseconds

3. Using Instant and Duration:

              If you are using java8 and above, this method is used. This program uses two packages java.time.Duration, java.time.Instant.

Ø  Read the starting time and ending time using Instant class ‘s now() function.

Ø  Now, create an object for Duration class. Find the difference by using between() method.

Ø  Print the value using System.out.println().

import java.time.Duration;

import java.time.Instant;

public class Exec {

    public static void main(String[] args) {

        // Reads the starting time

        Instant st = Instant.now();

        SimpleMeasure();

        // Reads the ending time

        Instant end = Instant.now();

        // let find the execution time using duration

        Duration timeElapsed = Duration.between(st, end);

        System.out.println("Execution time is: " + timeElapsed.toMillis() + " milliseconds");

    }

    public static void SimpleMeasure() {

        for (int i = 0; i < 1000000; i++) {

            // some work

        }

    }

}

The output is

Ø  Execution time is: 353477 milliseconds

These are the ways to get the execution time.

How to pass a lambda expression as a method argument in java??

                Lambda expression is introduced in Java SE8. It is used in functional interfaces. Functional interface has a single abstraction method. This is a block of code that doesn’t belong to any class.

Features:

  •   The functionality can be a method.
  • ·       The method is independent one.
  • ·       This function is used anywhere whenever the program needs.

How to pass a lambda expression as a method argument in java:

              It can be done many ways. Generally, we follow two methods.

1.      1. Using Runnable

2.       2.Using custom functional interface

1.Using Runnable :

       This method starts from creating a class “Main3” and save the program as “Main3.java”. In the public static void main(), add the lambda expression to print “Welcome to java Programming!”

Next, create a separate function execute with Runnable  variable action.

Now, call action.run().

public class Main3 {

    public static void main(String[] args) {

        //using a lambda expression as a method argument.

        execute(() -> System.out.println("Welcome to java Programming!"));

    }

    public static void execute(Runnable action) {

        action.run();

    }

}

This program gives you the below output.



2.Using custom functional interface

    A functional interface creates abstract method. Here, “condition” is the functional interface. The abstract method is “find”. It has two integer arguments.

A class “Main4” is created. It passes a lambda expression as argument. It adds two integer values.

Another function is created to call the lambda arguments.

Here, is the program.

interface condition {

    int find(int x, int y);

}

public class Main4 {

    public static void main(String[] args) {

        // Passing a lambda expression as a method argument

        int res = conditionChecking(45, 36, (x, y) -> x + y);

        System.out.println("Result: " + res);

    }

    public static int conditionChecking(int x, int y, Operation operation) {

        return operation.find(x, y);

    }

}

While executing this program, you get the below output.

These are the ways to pass a lambda expression as a method argument in java.

How to write a java program to implement merge sort??

               Sorting. It is a way of arranging data elements. There are many algorithms to perform sorting. One of the efficient algorithms is merge sort.

Who invented merge sort?

John von Neumann invented merge sort in 1945.

How the merge sort algorithm works?

              This algorithm uses divide and conquer concept.

  • ·       First, divide the entire list into sub lists. Each sub list should contain at least one element.
  • ·       Next, check each sub list and sort it separately. Repeat this process for all sub lists.
  • ·       Finally, all the sorted sub lists are merged.
  • Here, is the java program to implement merge sort.

//Java Program to implement merge sort.

import java.util.Arrays;

public class MergeSort {

      void merge(int array[], int a, int b, int c) {

        // Find sizes of two sub lists.

        int n1 = b - a + 1;

        int n2 = c - b;

        // creating Two  integer temp arrays

        int F[] = new int[n1];

        int S[] = new int[n2];

        // Loop to store data in temp arrays

        for (int i = 0; i < n1; ++i)

            F[i] = array[a + i];

        for (int j = 0; j < n2; ++j)

            S[j] = array[b + 1 + j];

        // Initialize the values of first and second sub lists

        int i = 0, j = 0;

        // Initialize the value of merged sub lists

        int k = a;

        while (i < n1 && j < n2) {

            if (F[i] <= S[j]) {

                array[k] = F[i];

                i++;

            } else {

                array[k] = S[j];

                j++;

            }

            k++;

        }

        // If there is any remaining elements in F[] then copy the elements. 

        while (i < n1) {

            array[k] = F[i];

            i++;

            k++;

        }

 

        //  If there is any remaining elements in S[] then copy the elements

        while (j < n2) {

            array[k] = S[j];

            j++;

            k++;

        }

    }

    // Merge sort begins

    void sort(int array[], int l, int r) {

        if (l < r) {

            // calculate the middle element

            int m = (l + r) / 2;

            // sort first and second half sublists.

            sort(array, l, m);

            sort(array, m + 1, r);

 

            // Merge the sublists

            merge(array, l, m, r);

        }

    }

    // Displaying the array elements

    static void printArray(int array[]) {

        int n = array.length;

        for (int i = 0; i < n; ++i)

            System.out.print(array[i] + " ");

        System.out.println();

    }

 

    // main function

    public static void main(String args[]) {

        int arr[] = {12, 11, 13, 5, 6, 7};

        System.out.println("Input array");

        printArray(arr);

        MergeSort ob = new MergeSort();

        ob.sort(arr, 0, arr.length - 1);

        System.out.println("\nThe array after merge sort");

        printArray(arr);

    }

}

  • ·       Save this program as “MergeSort.java”.
  • ·       Open a command prompt. Compile the program.
  • ·       Run the program like as follows.


 This is way of implementing merge sort algorithm in java.

Java Program to convert a stack trace to a string using StringWriter and PrintWriter:

               Whenever a program is written, it should be compiled and executed. Both of this process makes use of memory. During the time of execution, stack trace is generated. Stack trace is useful for debugging purpose.

  • ·       Let us create a java program to display stack trace.  It uses dumpStack() built in function.
  • ·       First, create a class Main1 and include the function calls demo(),demo1(),demo2() ,demo3() and demo4().
  • ·       Add the built in function call Thread.dumpStack() in demo4() .

public class Main1 {

  public static void main(String args[]) {

    demo();

  }

  static void demo() {

    demo1();

  }

  static void demo1() {

    demo2();

  }

  static void demo2() {

    demo3();

  }

  static void demo3() {

   demo4();

  }

  static void demo4()

  {

 Thread.dumpStack(); }

}

  • ·       Save this file as “Main1.java”. Compile and execute this file in command prompt.
  • ·       This will give you the output.

 Java program to convert a stack trace to a string using StringWriter and PrintWriter:

  • Import two built in packages java.io.Printwriter and java.io.StringWriter.

import java.io.PrintWriter;

import java.io.StringWriter;

//Create a class Main2 ans save it as “Main2.java”

public class Main2 {

    public static void main(String[] args) {

        try {

            //Here, a sample of exception (divide by zero) is created

            int a = 10 / 0;

        } catch (Exception e) {

            // A process of Converting a stack trace to a string

           // Create  objects for StringWriter and PrintWriter. Use the builtin function                       

            //  printStackTrace()

            StringWriter sw = new StringWriter();

            PrintWriter pw = new PrintWriter(sw);

            e.printStackTrace(pw);

            String stackTrace = sw.toString();

            // Display the stack trace as a string

            System.out.println("Stack Trace as a String:");

            System.out.println(stackTrace);

        }

    }

}

  • Compile and execute this program. This shows the output.
These are all ways to use stack trace.