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

}
}

}





No comments:

Post a Comment

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