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


br.lines().forEach(System.out::println);



// Read the line and sort


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

.forEach(System.out::println);


// 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"))

.forEach(System.out::println);

} catch (Exception e) {

// TODO: handle exception


e.printStackTrace();




}




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(",");

patt.splitAsStream("a,b,c").forEach(System.out::println);



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) {
  initCustomer();

  //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){
    System.out.println(c.name);
   }
  }

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


  /*Sort*/
  //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));
  /*Sort*/




  // 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)
    .average().getAsDouble();
  System.out.println(average);
  // Parallelism

  //Concurrent Reduction
  Map> byAge = customers.stream().collect(
    Collectors.groupingBy(Customer::getAge));

  System.out.println(byAge);


  /*code as data - explained*/

  Runnable oldTask=new Runnable() {
      @Override
      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
 @FunctionalInterface
 interface CheckCustomer {
  boolean test(Customer p);
 }

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

 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;
    System.out.println(multiply.eval(5));
 
    ArithmaticExpression sum = (x) -> x + x;
    System.out.println(sum.eval(5));
 
   }
  }
 /* 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;

}

@Override

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

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

}
}

}





Thursday, December 25, 2014

Finding log() without using Math.log()


Finding log for any given base and value in JAVA


import java.util.Scanner;

public class LogSolution {
static int scaleSize=1000000;
 public static void main(String[] args) throws Exception {
  Scanner in = new Scanner(System.in);
  double b = in.nextDouble();
  double T = in.nextDouble();

 //As per Logarithmic base change rule
  System.out.println(Math.log(T) / Math.log(b));

//Logarithm without Math.log() API
  System.out.println(log(b, T, 0));

 }

 private static double log(double base, double n, double log) {

  if (n == 1)
   return 0;

  if (n < base) {
   //Log base switch rule
   return 1 / log(n, base, log);
  }
  double value = 1;
  do {
   value *= base;
   log++;
  } while (value < n);

  if (value == n) {
   return log;
  }

  log--;
  return log(base, n, log, 1);
 }

 private static double log(double base, double n, double log,
   double precision) {
  double newPrecision = precision * 0.1d;

  double prevLog = log;
  for (int i = 1; i <= 10; i++) {
   double newLog = log + (i * newPrecision);
   double n2 = Math.pow(base, newLog);
   
   if (n == n2)
    return newLog;

   if (n < n2) {
    if (1 != (int) (newPrecision * scaleSize))
     return log(base, n, prevLog, newPrecision);
    else
     return prevLog;
   }
   prevLog = newLog;
  }

  return log;
 }
}


Logarithm rules

Logarithm product rule

logb(x × y) = logb(x) + logb(y)

Logarithm quotient rule

logb(x / y) = logb(x) - logb(y)

Logarithm power rule

logb(x ^ y) = y × logb(x)

Logarithm base switch rule

logb(c) = 1 / logc(b)

Logarithm base change rule

logb(x) = logc(x) / logc(b)

References:

RapidTables |
MATHisFUN

Recent Posts

Unix Commands | List all My Posts

Texts

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