Friday, December 18, 2015

symbolic link or symlink in unix linux


Whenever I do scripting or write any UNIX script I always write for symlinks rather than pointing to absolute path of directories in UNIX. It gives you flexibility of changing the symlink or soft link without making any change on your tried and tested scripts. I have worked on many different core Java projects which run on Linux and UNIX machine and make extensive use of UNIX symbolic links or symlinks.
Below are some of example of UNIX symlinks I have seen during my projects of involving UNIX soft links:

1) In our project our Java process picks latest version of package for executing, which is a UNIX soft link. So whenever we do a release, by using tar archives,  we just need to update latest UNIX symlink which makes release seamless and rollback very easy which in tern increases stability and predictability of our Java application.

2) All our UNIX script takes the location as argument so they are agnostic about the absolute path of resources and these resources are provided them via UNIX soft links and environment variables. This feature of our scripts saves a lot of time whenever we need to do any migration which involves changing location of resources.

3) An important point about UNIX soft link is that they inherit the permission of the directory , to which they are pointing out. which means if you change permission of directory by using  chmod command in Unix, permission on soft link will also be updated.

Creating a symbolic/Soft link


Here we will see how to create soft link and hard link in UNIX, also known as symbolic link or symlink in Linux.

$ ln -nsf 1.2 latest

This will create a soft link name “latest” which will point to directory “1.3”. Let’s see whether this soft link in UNIX created or not.  We can see that in last line a symlink is created. Notice lrwxrwxrwx  (first “l” denotes it is a link in UNIX)

Updating a symbolic/Soft link


We have seen how to create a symlink in UNIX now we will see how we can update that symlink or soft link  without removing it.

$ ln -nsf 1.3 latest

This will update the symlink latest to point to directory “1.2” instead of “1.3”. notice command line option “-nsf”. 

Removing a Symbolic/Soft Link


$ rm latest previous



if you liked this article help me buying the below nice MI Band 2


Tuesday, October 20, 2015

How to generate a CIRCULAR MATRIX using Multi-Dimensional Arrays

I have been asked to write a program for circular matrix in a interview programming round. 

Following program is a generic way of creating a circular matrix:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package blogspot.thinkwithjava;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 
 * @author R.D
 *
 */
class CircularMatrix {
 public static void main(String args[]) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter the number of elements : ");
  int n = Integer.parseInt(br.readLine());
  int A[][] = new int[n][n];
  int k = 1, c1 = 0, c2 = n - 1, r1 = 0, r2 = n - 1;
  while (k <= n * n) {
   for (int i = c1; i <= c2; i++) {
    A[r1][i] = k++;
   }
   for (int j = r1 + 1; j <= r2; j++) {
    A[j][c2] = k++;
   }
   for (int i = c2 - 1; i >= c1; i--) {
    A[r2][i] = k++;
   }
   for (int j = r2 - 1; j >= r1 + 1; j--) {
    A[j][c1] = k++;
   }
   c1++;
   c2--;
   r1++;
   r2--;
  }

  /* Printing the Circular Matrix */

  System.out.println("The Circular Matrix is:");
  for (int i = 0; i < n; i++) {
   for (int j = 0; j < n; j++) {
    System.out.print(A[i][j] + "\t");
   }
   System.out.println();
  }
 }
}

The output will look like this:




Wednesday, October 7, 2015

How to convert java.util.Date to java.sql.Date - JDBC Example


JDBC has their own data types for date and time e.g. java.sql.Date, java.sql.Time and java.sql.TimeStamp to match with database date, time and date time types, we cannot pass java.util.Date directly.
All methods which are suppose to store dates e.g. setDate(input1, input2) expects java.sql.Date, so it becomes essential to know how to convert java.util.Date to java.sql.Date in JDBC.

 You would be surprised to know that java.sql.Date is a subclass of java.util.Date and all it does is suppress or remove time-related fields from java.util.Date.

 It is also a good example of a class which violates Liskov substitution principle, because even though java.sql.Date extends java.util.Date, you cannot pass around it to the method which expect java.util.Date because all time-related methods e.g. getHour(), getMinute() and getSeconds() method throws java.util.NotSupportedException.


Converting java.util.Date to java.sql.Date - Example


Unfortunately, there is no method like toSQLDate() in java.util.Date class to facilitate conversion between util date and SQL date but you can use getTime() method to extract long millisecond value from java.util.Date and create a new java.sql.Date based upon that value as shown below:

Date now = new Date();

java.sql.Date sqlDate = new java.sql.Date(now.getTime());

This is the easiest and right way to convert a java.util.Date to java.sql.Date in Java.


Here is a good java book available on Amazon.Head First Java

Wednesday, September 23, 2015

how to read file into string in java 8

Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write lot of boilerplate code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on.

Reading File to String in Java

In order to understand the beauty of Java 7 way of reading the file into String, first, let's see how we used to do it on Java 1.5 and 6.

InputStream is = new FileInputStream("manifest.mf");
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
        
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
        
while(line != null){
   sb.append(line).append("\n");
   line = buf.readLine();
}
String fileAsString = sb.toString();
System.out.println("Contents : " + fileAsString);

You can see that it's not easy, you need to write a lot of unnecessary boilerplate code. This is even when we are just writing for the demo, forget about production quality code when you have to handle exceptions properly. Worth noting is that, in this example we are using platform's default character encoding, which is fine because manifest.mf has not contained any character other than ASCII, but it's not a safe way, if you don't know the encoding, by default use "UTF-8". Now let's see how you can read a file as String in JDK 1.7
String contents = new String(Files.readAllBytes(Paths.get("manifest.mf")));
System.out.println("Contents (Java 7) : " + contents);
You can see there is no more wrapping around different class, no more loop, no more handling of special condition, just a method call to read whole file as byte array and then create String from it. Just like our previous example, this is also using platform's default character encoding. Let's see how can we provide a custom character encoding of our choice:
String fileString = new String(Files.readAllBytes(Paths.get("manifest.mf")), StandardCharsets.UTF_8);
System.out.println("Contents (Java 7 with character encoding ) : " + fileString);
Now does it get any simpler with Java 8 Streams and lambda expression, well it does, as we have seen on my earlier article about how to read file in Java 8, its same as Java 7, how can you go less than one line, but yes you can use Stream and its lazy evaluation for your benefit :
Files.lines(Paths.get("manifest.mf"), StandardCharsets.UTF_8).forEach(System.out::println);

You should get familiar with new File API, it's really helpful to do efficient file IO in Java, as shown below: How to read file into String in Java 8
package thinkwithjava;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;


/**
 * Java Program to demonstrate different ways to loop over collection in 
 * pre Java 8 and Java 8 world using Stream's forEach method.
 * @author RD
 */
public class FileToStringJava8 {

    public static void main(String args[]) throws IOException {

        // How to read file into String before Java 7
        InputStream is = new FileInputStream("manifest.mf");
        BufferedReader buf = new BufferedReader(new InputStreamReader(is));
        
        String line = buf.readLine();
        StringBuilder sb = new StringBuilder();
        
        while(line != null){
            sb.append(line).append("\n");
            line = buf.readLine();
        }
        
        String fileAsString = sb.toString();
        System.out.println("Contents (before Java 7) : " + fileAsString);
        
        
        // Reading file into Stirng in one line in JDK 7
        String contents = new String(Files.readAllBytes(Paths.get("manifest.mf")));
        System.out.println("Contents (Java 7) : " + contents);
        
        
        
        // Reading file into String using proper character encoding
        String fileString = new String(Files.readAllBytes(Paths.get("manifest.mf")), StandardCharsets.UTF_8);
        System.out.println("Contents (Java 7 with character encoding ) : " + fileString);
        

        // It's even easier in Java 8
        Files.lines(Paths.get("manifest.mf"), StandardCharsets.UTF_8).forEach(System.out::println);
        
    }


}

That's all about how to read the file into String in Java. Though this is good for the small tasks where you need contents of file as String in your program, don't read a large file of few Gigabytes like that, otherwise your Java program will run out of memory, instead use InputStream. Also, always remember to use character encoding while converting binary data to character data. If you are unsure, just use UTF-8 as default.

Friday, September 11, 2015

Generic Type changes and improvements in Java 8

Java 8 propose some improvements to the existing type-argument inference support that will significantly reduce the need for explicit type-arguments in generic method calls.
1.     Inference in argument position
Consider the following class declaration:

class List {
   static  List nil() { ... };
   static  List cons(Z head, List tail) { ... };
   E head() { ... }
}

The result of a generic method, such as List.nil() may be inferred from the right-hand side of an assignment:

List ls = List.nil();

The compiler's type-inference mechanism figures out that the type-argument to the List.nil() call is indeed String. It seems reasonable that the compiler should be able to infer the type when the result of such a generic method invocation is passed to another method, as below:
List.cons(42, List.nil()); //error: expected List of Integer , found List of Object

Unfortunately, this is not allowed in JDK 5/6/7 -- the only option available to the programmer is to use an explicit type-argument:
List.cons(42, List.nil());

It would be nice if type-argument inference would be extended to consider the formal parameter type in a method call (target typing).

2.  Inference in chained calls

Another fairly common problem is when generic method calls are chained together, as below:
String s = List.nil().head(); //error: expected String, found Object

The right-hand type in the above assignment is unused during type-argument inference -- as a result, the only option for the programmer is (again) to manually specify type-arguments, as in:
String s = List.nil().head();

Again, it would be nice to remove the burden of explicit type-arguments by allowing the right-hand type of the assignment (String) to flow through the chain of generic method calls.


Switch in Java 7

In java 7 we got some significant improvement that is worth noting. Before Java 7 it was only possible to check Integer expressions in switch statements but after Java 7 you can use String Object in the expression of a switch statement.

Example:
/**
 * 
 */
package com.blogspot.thinkwithjava;

/**
 * Program to show the use of String comparison in Switch statements
 * 
 * @author RD
 * 
 */
public class SwitchWithString {

 public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
  String typeOfDay;
  switch (dayOfWeekArg) {
  case "Monday":
   typeOfDay = "Start of work week";
   break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
   typeOfDay = "Midweek";
   break;
  case "Friday":
   typeOfDay = "End of work week";
   break;
  case "Saturday":
  case "Sunday":
   typeOfDay = "Weekend";
   break;
  default:
   throw new IllegalArgumentException("Invalid day of the week: "
     + dayOfWeekArg);
  }
  return typeOfDay;
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  SwitchWithString sws = new SwitchWithString();

  System.out.println("Monday is a "
    + sws.getTypeOfDayWithSwitchStatement("Monday"));

 }

}

Output is: Monday is a Start of work week


Monday, September 7, 2015

Different ways of calculating Factorial in java

Problem : Write a program to calculate factorial of a given number in Java.

Explanation: If you come from Maths background then you know that factorial of a number is number*(factorial of number -1). You will use this formula to calculate factorial in this  Java tutorial. Since factorial is a naturally recursive operation, it make sense to use recursion to solve this problem but its not always the best way.

By the way, factorial of numbers grows very quickly and even the largest integral data type in Java, long is not able to hold factorial of anything or above 50. In such cases you can use BigInteger, which has theoretically no limit and can be used to represent very large integral numbers.
We can calculate Factorial by following 3 ways:

  1. Using recursion 
  2. Using Loop
  3. Using Dynamic Programming.
Solution 1 : Factorial using recursion

In order to create a recursive solution you need a base case where program terminates and in this problem base case is factorial of 1, which is 1. So if given number is greater than 1, we keep applying factorial formula and recursive call this method with n - 1 as shown below :

public static long factorial(int number){        
        //base case - factorial of 0 or 1 is 1
        if(number <=1){
            return 1;
        }        
        return number*factorial(number - 1);
    }

Once input become 1 the method stopped recursive call and return 1. From there onward stack started to roll down and finally factorial of number is calculated.

Example:
import java.util.Scanner;

/** Java Program to calculate factorial using loop
 *
 * @author RD 
 * 
 **/

public class Factorial {

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter the number whose factorial is to be found: ");
       int n = scanner.nextInt();
       int result = factorial(n);
       System.out.println("The factorial of " + n + " is " + result);
   }

   public static int factorial(int n) {
       int result = 1;
       for (int i = 1; i <= n; i++) {
           result = result * i;
       }
       return result;
   }
}


Solution 2 : Factorial using loop
As I said instead of using recursion and calling factorial method again you can also use for loop to calculate factorial because !n = n*(n-1)*(n-2).....*1 , which can easily be implemented using loop as shown below :


public static long factorial(long input){
        long factorial = 1L;
        for(long i= input; i > 0; i--){
            factorial = factorial * i;
        }
        
        return factorial;
    }
You can see that we start with the number and multiply it with the factorial which is initialized with 1 then we reduce the number by 1 until number becomes 1, which is nothing but n*(n-1)*(n-2).....*1.  
Why we use Recursion in methods? 

  1. Code is easier to read 
  2. Less lines of code
  3. Problem solving approach is somewhat divide and conquer: Solve bigger problem by solving simpler sub problems.
Example
/**
  * Java Factorial Using Recursion Example
  * This Java example shows how to generate factorial of a given number using recursive function.
  * @author RD
**/
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class JavaFactorialUsingRecursion {
       
        public static void main(String args[]) throws NumberFormatException, IOException{
               
                System.out.println("Enter the number: ");
               
                //get input from the user
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                int a = Integer.parseInt(br.readLine());
               
                //call the recursive function to generate factorial
                int result= fact(a);
               
               
                System.out.println("Factorial of the number is: " + result);
        }
       
        static int fact(int b)
        {
                if(b <= 1)
                        //if the number is 1 then return 1
                        return 1;
                else
                        //else call the same function with the value - 1
                        return b * fact(b-1);
        }
}

Solution 3 : Factorial using dynamic programming

Dynamic Programming is similar to Recursion in which we break the problem into subproblems and use them to arrive at the final solution. However, it is different from Recursion as we store results of already solved subproblems to avoid re- calculation. Caching of results leads to better time complexity of code at the cost of space complexity.



public static long factorial(int n)
{
    if (n >= 0) 
    {
        result[0] = 1;
        for (int i = 1; i <= n; ++i) 
        {
            result[i] = i * result[i - 1];
        }
        return result[n];
    }
}
Dynamic Programming approach will be caching the solved sub problems and will be more efficiently execute in linear time.

Friday, September 4, 2015

Oracle Nashorn! The Node.js on JVM

Oracle Nashorn: A Next-Generation JavaScript Engine for the JVM


Nashorn is the new JavaScript Runtime that comes with Java 8 and runs on the JVM.

In this post we will see how to run simple 
Node.js applications with Nashorn on the JVM.

Avatar.js is a project to bring the node programming model, APIs and module ecosystem to the Java platform. Unfortunately Avatar.js does not officially provide a binary distribution and the build process looks quite intricate (involving Python and C++).

There is also 
Project Avatar, an upcoming web-platform by Oracle. Project Avatar builds uponAvatar.js.

By reverse-engineering Project Avatar I found the necessary artefacts of Avatar.js in the java.net Maven repository. These artefacts can be used to run Node applications with Avatar.js without having to build Avatar.js yourself.

The following steps show how to run a simple Node.js web application on OSX. The steps should be very similar for Linux or Windows.

1.            Download avatar-js.jar from the java.net Maven Repo.
Current version is here:https://maven.java.net/content/repositories/public/com/oracle/avatar-js/0.10.25-SNAPSHOT/
Example file: avatar-js-0.10.25-20140313.063039-43.jar 

2.            Download the native library avatar-js.dylib from the java.net Maven Repo.
Current version is here:https://maven.java.net/content/repositories/public/com/oracle/libavatar-js-macosx-x64/0.10.25-SNAPSHOT/
Example file: libavatar-js-macosx-x64-0.10.25-20140312.062209-35.dylib
For Linux you would download the corresponding 
.so file from ../libavatar-js-linux-x64/0.10.25-SNAPSHOT/
For Windows you would download the corresponding 
.dll file from ../libavatar-js-win-x64/0.10.25-SNAPSHOT/

3.            Rename the native library to avatar-js.dylib and rename the jar to avatar-js.jarand put both in a directory called dist

4.            Create a simple Node.js app in the a file called app.js:

var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

Run the command: 
java -Djava.library.path=dist -jar dist/avatar-js.jar app.js

  1. The output should be: Server running at http://127.0.0.1:8000/ 
  2.  Navigate to  http://localhost:8000/

Wednesday, September 2, 2015

How to use BigInteger class in Java

Some time we need to store some really big numbers. Though we are already using the primitive data types int and long. But sometime we need to store values which cannot be held by these data type.

We will understand the problem with the help of factorial calculation as follows:

If we are calculating factorial of 13 or more and will try to store it in int datatype then we will not get the correct result, and this will result in overflow.
Again if we are calculating factorial of 21 or more it cannot be held through long data type. It will give the same error as mentioned above.

To hold the factorial of 21 or more we need BigInteger class of java.math package. As name suggests BigInteger class is used to hold the really big number, something which is even bigger than maximum value of long primitive

e.g. 2^63 -1 or 9223372036854775807L. The java.math.BigInteger class provides all the operation similar to Java’s integer primitive and have all the relevant methods from Java.Math.

To declare a BigInteger we use:

BigInteger number = BigInteger.valueOf(long number);
Also worth noting that, similar to java.lang.String and other wrapper classes BigInteger is also Immutable in Java, which means its important to store result back into same variable, otherwise result of calculation will be lost. BigInteger stores numbers as 2's complement number like int primitive and support operation supported by int variables and all relevant methods from java.lang.Math class. Additionally it also provide support for modular arithmetic, bit manipulation, primality testing, prime generation, GCD calculation and other miscellaneous operations.

Important things about BigInteger class in Java
BigInteger class in Java is designed to deal with really large numbers in Java, but to do that it’s very important that you make yourself familiar with class. Here are some key points about java.math.BigInteger class :

1. The BigInteger class is used to represent arbitrarily large numbers. Overflow doesn't occur as is the case with int and long primitive.

2. The BigInteger class is immutable which means that the object on which the multiply function was invoked doesn't change the integer it is holding. The multiplication is performed and a new BigInteger is returned which needs to be stored in the variable fact.

3. BigInteger provides operations similar to int primitive type in Java, additionally it provide support for prime generation, bit manipulation, GCD calculations etc.

4. You can create BigInteger object by giving number as String or byte array using constructor, or you can convert a long value to BigInteger using valueOf() method as shown below :

BigInteger bigIntegerFromLong = BigInteger.valueOf(292909333L);
BigInteger bigIntegerFromString = new BigInteger("338948938948");
Java Program to Calculate Factorial of Large Number

Here is our sample Java program to calculate factorial for large numbers, well given number is not exactly large but the factorial value is definitely large. For example, factorial of 45 is 119622220865480194561963161495657715064383733760000000000, which is clearly out of bound for even a long data type. Since theoretically BigInteger has no limit it can hold these values as shown in following example.
There are many ways to calculate factorial like using recursion, dynamic programming or iteration. In following example we have used iteration to calculate factorial in Java.


import java.math.BigInteger;

/**
 * Write a Java program to calculate factorial of large numbers using
 * BigInteger.
 *
 * @author RD
 *
 */
public class LargeFactorialDemo {

    public static void main(String args[]) {

        System.out.printf("Factorial of 32 is %s %n", factorial(32));
        System.out.printf("Factorial of 0 is %s %n", factorial(0));
        System.out.printf("Factorial of 1 is %s %n", factorial(1));
        System.out.printf("Factorial of 5 is %s %n", factorial(5));
        System.out.printf("Factorial of 41 is %s %n", factorial(41));
        System.out.printf("Factorial of 45 is %s %n", factorial(45));

    }

    /*
     * Java method to calculate factorial of a large number
     * @return BigInteger factorial of given number
     */
    public static BigInteger factorial(int number) {
        BigInteger factorial = BigInteger.ONE;

        for (int i = number; i > 0; i--) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }

        return factorial;
    }

}

Output
Factorial of 32 is 263130836933693530167218012160000000
Factorial of 0 is 1
Factorial of 1 is 1
Factorial of 5 is 120
Factorial of 41 is 33452526613163807108170062053440751665152000000000
Factorial of 45 is 119622220865480194561963161495657715064383733760000000000

You can see that how large factorial of 45 is, clearly its not possible to use long data type to store such huge integral values. You need to use BigInteger class to store such big values.


Hope you liked the post. Please consider leaving a comment and follow the blog.

Thursday, August 20, 2015

Loop iteration redefined with java 8 Stream


for loop is there in many programming languages like C, C++ java C# etc and it is used mainly iterating contents of same type.

for loop has come a long way in Java 8 with new forEach() method in java.util.stream.Stream class.

We will check in the following post how every release of java has given us more and more compact and enhanced looping experience by time.

Pre JDK 1.5, this was the way of iterating over an Collection let’s say ArrayList:
// Before JDK 1.5, printing each element of List using for
List  countries = Arrays.asList("India", "Australia", "England", "South Africa");

for(int i=0; i < countries.size(); i++)
{
  System.out.println(countries.get(i));
}
So when foreach loop or advanced for loop was added on Java 5, we started to following style of looping over Collection or List :
for(String country : countries){
      System.out.println(country);
}
This was much shorter, cleaner and less error prone than previous one and everybody loved it. You don't need to keep track of index, you don't need to call size() method in every step and it was less error prone than previous one, but it was still imperative. You are telling compiler what to do and how to do like traditional for loop.

Now comes the era of Lambda Expressions where things changes drastically when functional style of programming was introduced in Java 8 via lambda expression and new Stream API. Now you can loop over your collection without any loop in Java, you just need to use forEach() method of java.util.Stream class, as shown below :

countries.stream().forEach(str -> System.out.println(str));


This code has reduced looping over collection or list into just one line.
To add into, If you want to perform some pre processing task e.g. filtering, conversion or mapping, you can also do this in same line, as shown below:

countries.stream().filter(country ->
country.contains("n")).forEach(str -> System.out.println(str));

Wednesday, August 19, 2015

Time and Date APIs in Java 8

The standard date and time classes prior to Java SE 8 are poor. By tackling this problem head-on, Joda-Time has become the de facto standard date and time library for Java.

For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code.

Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.

These issues, and several others, have led to the popularity of third-party date and time libraries, such as Joda-Time

The new changes will appear in the Java SE8 package java.time.

A selection of key features:
  • LocalDate - date without time
  • LocalTime - time without date
  • Instant - an instantaneous point on the time-line
  • DateTime - full date and time with time-zone
  • DateTimeZone - a better time-zone
  • Duration and Period - amounts of time
  • Interval - the time between two instants
  • A comprehensive and flexible formatter-parser

Tuesday, August 18, 2015

Stream Collection types

Java is inheritably sequential and there is no direct mean to introduce parallel processing at library level, Stream API is going to fill that gap. By using this, you can filter elements of collection on given criterion e.g. if you have a List of employees, you can filter all employees based upon their name, department and so on.

Stream API allows you to process Collection both sequentially and parallel. This is also useful for bulk data operation. You can create a sequential and parallel stream as follows :

List employees = getListOfEmployees();
 
// sequential version
Stream  stream = employees.stream();
 
//parallel version
Stream  parallelStream = employees.parallelStream();

Collection and Stream

Collection interface is enhanced to provide stream support. It now has a stream() method which returns a sequential Stream with this collection as its source. Once you get the reference of stream, you can perform bulk data operations with this collection.

One of the important things to note is that Stream do not modify the original source. For every operation, a new Stream is created and original collection remains unmodified. Similarly, you cannot reuse Stream either. Reusing a closed stream will throw IllegalStateException as shown below:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
    at java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)
    at java.util.stream.ReferencePipeline.(ReferencePipeline.java:94)
    at java.util.stream.ReferencePipeline$StatelessOp.(ReferencePipeline.java:618)
    at java.util.stream.ReferencePipeline$2.(ReferencePipeline.java:163)
    at java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:162)
    at Test.main(Test.java:33)

It supports functional programming idioms such as map and reduce along with parallel processing capability, support for filtering elements from Collection.


Stream operations 

Stream operations are mainly divided into two categories : intermediate and terminal operations. Intermediate operations such as filter() or map() returns a new Stream, while terminal operations such as Stream.forEach() produce a result or side effect. After the terminal operation, the stream pipeline is considered consumed, and can no longer be used.

Intermediate operations are also of two types stateless and stateful. As name suggests, stateless operations doesn't retain any state from previously processed element. For example : filter() and map(). On the other hand distinct() and sorted() are example of stateful operations, which can have state from previously processed elements, while processing new elements.

Important methods in java.util.stream

Return Type
Method Name
Short Description
Long
count()
Returns the count of elements in this stream
Stream
Distinct()
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
static Stream
Empty()
Returns an empty sequential Stream.
Stream
Filter(Predicate predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.
Stream
flatMap(Function> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
void
forEach(Consumer action)
Performs an action for each element of this stream.
static Stream
generate(Supplier s)
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.
static Stream
iterate(T seed, UnaryOperator f)
Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.
Stream
Limit(long maxSize)
Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
Stream
map(Function mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream.
Optional  
max(Comparator comparator)
Returns the maximum element of this stream according to the provided Comparator.
Optional  
min(Comparator comparator)
Returns the minimum element of this stream according to the provided Comparator.
Stream
skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.
Stream
sorted()
Returns a stream consisting of the elements of this stream, sorted according to natural order.
Stream
Sorted (Comparator comparator)
Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
Object[]
toArray()
Returns an array containing the elements of this stream.

Tuesday, August 11, 2015

Default Methods

Default Methods in Java 8

In my previous articles, we have looked at LambdaExpressions and Method References. In this latest article in the series, we will be looking at Default methods.


What is Default method?

Default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.

We specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature. All method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.

Extending Interfaces that contains default methods

When you extend an interface that contains a default method, you can do following:
  • Not mention the default method at all, which lets your extended interface inherit the default method.
  • Re declares the default method, which makes it abstract.
  • Redefine the default method, which overrides it.

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...