Tuesday, December 30, 2014

JDK 7 : try-with-resources

The try-with-resources Statement

There is a big full stop for the resource leak in JAVA.
Instead of breaking our heads to properly releasing used resources after its usage,
from JAVA SE 7 onwards we just need to focus only on business using those resources.
Past couple of decades, we followed as best practice in releasing the resource using the finally block.

FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(new FileReader("text.txt));
try {
   System.out.println( br.readLine());
} finally {
 if (br != null) br.close();
 if (fr != null) fr.close();

Many of the close() function implementation will close themself, and makes a no mark in system.
However, few times it may do additional task to release its parent also. For instance, ResultSet.close() implementations.

From JDK 7 onwards, any resource object which extends either java.lang.AutoCloseable or java.lang.Closeable can be instanciated in try statement. Those resources automatically get closed after try block executions.
For the resource implementor, its recommended not to throw any exception while doing close() call.
And align the resource close operation such that it is closing itself.

try (FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(fr)) {
System.out.println( br.readLine());

JDK 8: Stream API

Stream API

  • The Stream interface is located in the java.util.stream package.
  • It represents a sequence of objects somewhat like the Iterator interface. However, unlike the Iterator, it supports parallel execution.
  • The Stream interface supports the map/filter/reduce pattern and executes lazily, forming the basis (along with lambdas) for functional-style programming in Java 8.
  • There are also corresponding primitive streams (IntStream, DoubleStream, and LongStream) for performance reasons.

How to create Stream which are multi core friendly

try (FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(fr)) {

// Read the line and Print


// Read the line and sort

br.lines().sorted(( x1, x2) -> x1.compareTo(x2))


// Read the line and sort and filter and finally print

br.lines().sorted((String x1, String x2) -> x1.compareTo(x2))

.filter(line -> line.contains("x"))


} catch (Exception e) {

// TODO: handle exception



Stream API operations

  • There are several static methods on the  java.nio.file.Files class for navigating file trees using a Stream.
  • list(Path dir) – Stream of files in the given directory.
  • walk(Path dir)– Stream that traverses the file tree depth-first starting at the given directory.
  • walk(Path dir, int maxDepth) – Same as walk(dir) but with a maximum depth.
  • Streaming text pattern
Pattern patt = Pattern.compile(",");


Monday, December 29, 2014

JDK 8: Lambda

  • Lambda provides a clear and concise way to represent one method interface using an expression.
  • Lambda expressions also improve the Collection libraries making it easier to iterate through filter, map, collect data from a Collection.
  • In addition, new concurrency features improve performance in multi-core environments.

Below few samples and usages explained.

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class LambdaTest {
 public static Random r = new Random();
 static List customers = new ArrayList<>();
 public static void main(String[] args) {

  //Simple Lambda expression
  customers.stream().forEach(c -> System.out.println(c.name));

  //filter operation
  for (Customer c : customers){
   if (c.age > 30 && c.age < 39){

  customers.stream().filter(c -> c.age > 30 && c.age < 39).forEach(name -> System.out.println(name));

  //No lambda
  Collections.sort(customers, new Comparator() {
   public int compare(Customer c1, Customer c2){
    return c1.age.compareTo(c2.age);

  //Using Lambda dsc
  Collections.sort(customers, (Customer c1, Customer c2) -> c2.age.compareTo(c1.age));

  //Using Lambda asc
  Collections.sort(customers, (Customer c1, Customer c2) -> c1.age.compareTo(c2.age));

  //Using Lambda asc - Lambda supports "target typing" which infers the object type from the context in which it is used.
  Collections.sort(customers, ( c1,  c2) -> c1.age.compareTo(c2.age));

  // Method Reference
  String[] stringArray = { "Barbara", "James", "Mary", "John",
    "Patricia", "Robert", "Michael", "Linda" };
  Arrays.sort(stringArray, String::compareToIgnoreCase);
  // Method Reference

  // Parallelism
  double average = customers.parallelStream().mapToInt(Customer::getAge)
  // Parallelism

  //Concurrent Reduction
  Map> byAge = customers.stream().collect(


  /*code as data - explained*/

  Runnable oldTask=new Runnable() {
      public void run() {
          System.out.println("I am Runnable");

  Runnable newTask = () -> System.out.println("I am Runnable");
  Thread t1=new Thread(oldTask);
  Thread t2=new Thread(newTask);

  File files=new File("/tmp");
  File[] existingfiles = files.listFiles(file -> file.isFile());

  /*code as data - explained*/


 private static void initCustomer() {
  for (int i = 0; i < 100; i++) {
   customers.add(new Customer(Math.abs(r.nextInt()%100)));

 //Functional interface demo
 interface CheckCustomer {
  boolean test(Customer p);

 public static void printCustomer(List roster,
   CheckCustomer tester) {
  for (Customer p : roster) {
   if (tester.test(p)) {

 public static void personTest() {
  List roster = new ArrayList();
  printCustomer(roster, p -> p.age >= 18 && p.age <= 25);
 //Functional interface demo

 /* 1-ary Lambda expression*/
  interface ArithmaticExpression {
   Y eval(X x);

  class Sample3 {
   public void MainMethod() {
    ArithmaticExpression multiply = (x) -> x * x;
    ArithmaticExpression sum = (x) -> x + x;
 /* 1-ary Lambda expression */

class Customer {
public String name;
public Integer age;

public Customer() {


public Customer(int age) {
this.age = age;
name = "name" + age;


public String getName() {
return name;


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


public Integer getAge() {
return age;


public void setAge(Integer age) {
this.age = age;



public String toString() {
return "Customer [name=" + name + ", age=" + age + "]";

public void printCustomer() {
System.out.println("Name:" + name + " Age: " + age + " \n");



Recent Posts

Unix Commands | List all My Posts


This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com