Thursday, February 23, 2017

Lambdas in Java(1.8) - 5 - Streams API - iterations simplified / MethodReference

Collection.stream()

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class Java8StreamsToPrintList {

public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Gallen","Burchhill"),
new Person("Allen","churchhill"),
new Person("Alex","garten"),
new Person("Sam","Batley"));

people.stream()
.filter(person-> person.firstName.startsWith("A"))
.forEach(person->System.out.println(person));

System.out.println("---------------------------------");

int numberOfPplStartsWithA = 
(int) people.stream()
.filter(person-> person.firstName.startsWith("A"))
.count();
System.out.println(numberOfPplStartsWithA);

System.out.println("--------METHOD REFERENCE, equivalent-----------");
//Using Method reference to print all values in List
printAllPeople(people,System.out::println);
               //System.out::println is same as person->System.out.println(person)
}

private static void printAllPeople(List<Person> people, Consumer<Person> consumer) {
for (Person person: people) {
consumer.accept(person);
}

}

}


______________________________________________________________________________

Lambdas in Java(1.8) - 4 - Simplified List operations using Lambdas

Simplified List operations using Lambdas

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class Lambdas_ListOperations {

public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Gallen","Burchhill"),
new Person("Allen","churchhill"),
new Person("Alex","garten"),
new Person("Sam","Batley"));

//Sorting List the usual way
// Collections.sort(people,new Comparator<Person>(){
// @Override
// public int compare(Person person1, Person person2) {
// return person1.firstName.compareTo(person2.firstName);
// };
// });
//(OR)
//Sorting List the Lambda way
Collections.sort(people, 
                                       (person1,person2)-> person1.firstName.compareTo(person2.firstName));


               //PRINT all using regular method
// for(Person person : people){
// System.out.println(person.firstName);
// }
//(OR)
//PRINT all the Lambda way
printAllFromListUsingLambdas(people,
                                                                   (person1)->System.out.println(person1.firstName));

 //PRINT all users with firstNames starting with "A"
//               printConditionally(people);
//(OR)
                //PRINT all users with firstNames starting with "A" the Lambda way
printConditionallyUsingLambdas(people,
person1->person1.firstName.startsWith("A"),
person1->System.out.println(person1.firstName));
}

private static void printConditionallyUsingLambdas(List<Person> people, Predicate<Person> predicate, Consumer<Person> consumer) {
for(Person person1 : people){
if(predicate.test(person1)) consumer.accept(person1);
}
}

private static void printAllFromListUsingLambdas(List<Person> people, Consumer<Person> consumer) {
for(Person person : people)
{
consumer.accept(person);
}
}

private static void printConditionally(List<Person> people) {
for(Person person : people){
if(person.firstName.startsWith("A")) System.out.println(person.firstName);
}
}
}

class Person{
String firstName;
String lastName;

public Person(String firstName,String lastName) {
this.firstName = firstName;
this.lastName=lastName;
}

@Override
public String toString() {
return this.firstName+" "+this.lastName;
}
}


Note:
 Important out-of-the-box APIs provided in java 8(java.util.Function.Predicate)
  • Consumer<Object>..Its a functional method with a single method called accept(Object). This method takes in an object but returns nothing.. instead it s accept method can be implemented in printing or performing some logic as in the above example.
  • Predicate<Object>..Its a functional Interface with a single method called test(Object) and returns a boolean. This method takes in an object and returns boolean.. Its test method can be implemented in checking a certain condition as in the example above
  • BiCosumer<Object1, Object2>..This Functional interface is very similar to Consumer interface.. the only difference is that it takes 2 objects and returns nothing as in Consumer.

  1. There are many more OOTB interfaces provided in java 8 for Lambda usage.
  2. @FunctionaInterface is the annotation that can you used above an interface that is intended for Lambda functions. This way, the developers can be informed of the interfaces that are used in code by Lambda declarations; which in turn will disable them from altering it.
________________________________________________________________________

Lambdas in Java(1.8) - 3 - Anonymous InnerClass replaced with Lambda



Replace Anonymous inner classes with Lambdas.

A classic situation of using Lambda to replace an anonymous class, with Only one method(a must condition) is the Thread declaration that implements an inner Runnable interface as below:


public class ReplaceAnonymousWithLambda {
public static void main(String[] args) {
//Using Runnable anonymour inner class
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("run() executed from Runnable Anonymous inner class");
}
});
//-----------------(A)
thread.run();

//Using Lambda function as a replacement for the Runnable anoynymous class
thread = new Thread(()->System.out.println("contents as in run() using Lambda exp"));
//-----------------(B)
thread.run();
}

}

Lambdas in Java(1.8) - 2 - Lambda Passed as method argument Example

LambdaInterface 
(or) 
Lambda Expression as Method Argument

public class PassingLambdaAsMethodArgument {

void printGreeting(GreetingLambdaInterface greetingLambdaInterface){
System.out.println(greetingLambdaInterface.printGreetingStrLength("hallo") );//print the length of string "hallo"
}

public static void main(String[] args) {
PassingLambdaAsMethodArgument plafp = new PassingLambdaAsMethodArgument();

//Pass lambda Interface object as method argument
GreetingLambdaInterface gli = s->s.length();
plafp.printGreeting( gli );

//(OR) 

               //pass the lambda expression as method argument
plafp.printGreeting(s->s.length());
}
}

interface GreetingLambdaInterface {
int printGreetingStrLength(String s);
}

Lambdas in Java(1.8) - 1


Lambdas

reference :https://www.youtube.com/watch?v=gpIUfj3KaOc

They are a concept of passing a method definition itself in a very short form over passing and argument using a method definition.
In other words, A piece of code gets assigned to a method itself (a block of code) .
Something like :

  • aBlockofCode = public void perform(){System.out.print("Hello");}... All Lambda expressions are in orange text below:
However, with the right syntax:
  • Ex 1: aBlockofCode= () -> {System.out.print("Hello");}
  • the bolded expression is a lambda expression.
  • //note that  ";" is within the curly braces
  • The braces is not requires if the block of code contains only one statement.
  • Ex 2: aBlockofCode= (int a) -> a*2;//here, the functions takes a param int a, and returns (a*2). The statement "return" is ignored here, since blocking(using curly braces for multiple statments) is not required. However, if block of code, return needs to be defnied wenevr required.
  • Ex 3: aBlockofCode=  (int a,int b) -> { 
if(b==0) return 0; 
    return a/b;
      };
      • Ex 4: aBlockofCode= (String s) -> s.length();

      While the orange text is referring a lambda expression, a lambda expression can be defined as a interface. Refer the examples below for more understanding:

      public class Lambdas {
      public static void main(String[] args) {
      PrintHalloLambdaInterface halloVarLambda = ()->System.out.println("hello");// --(A)
      halloVarLambda.PrintHalloMethod();
      AddParamsLambdaInterface addParams = (int a, int b)->a+b;// --(B)
      System.out.println(addParams.PrintSum(2, 3));
      StringLengthLambdaInterface strLenLambda =(String s)->s.length();// --(C)
      System.out.println(strLenLambda.PrintStrLength("StringLength"));
      }

      interface PrintHalloLambdaInterface{
       void PrintHalloMethod(); //param not taken or returns- implemented body in//  --(A)
      }
      interface AddParamsLambdaInterface{
       int PrintSum(int a, int b);//2 int params taken and returns an int- implemented body in // --(B)
      }
      interface StringLengthLambdaInterface{
       int PrintStrLength(String str);
      }
      }


      Note:
      • TYPE INFERENCE - Replacing "String s" with just "s" is valid in --(C)
        • StringLengthLambdaInterface strLenLambda = s ->s.length();// --(C)
      • A LambdaInterface can have only one abstract method(Functional Interface) that matches the lambda 



      Wednesday, February 8, 2017

      7-java.lang.Math (javaSE-1.8)

      java.lang.Math (javaSE-1.8)


      Math.E :2.718281828459045   //returns number closer to another other natural logs
      --------------------------------------------------------------
      Math.PI :3.141592653589793
      --------------------------------------------------------------
      Math.addExact(3, -790) :-4 //adds arguments
      Math.subtractExact(3,-7) :10 //subtracts arguments
      Math.decrementExact(4) :3 //decrement argument by 1
      Math.incrementExact(4) :5: //increments argument by 1
      Math.multiplyExact(3,4) :12
      Math.negateExact(3) :-3
      --------------------------------------------------------------
      Math.cbrt(8) :2.0
      Math.sqrt(4) :2.0
      Math.abs(-32.54536) :32.54536 //removes negation
      Math.max(34, 34.2) :34.2
      Math.min(34, 34.2) :34.0
      Math.nextAfter(3, 5) :3.0000002 ://returns closed of the first towards teh second
      Math.pow(2, 3) :8.0
      Math.random() :0.9903858200332046
      Math.round(3.569) :4
      Math.rint(5.6) :6.0
      --------------------------------------------------------------
      Math.ceil(3.4) :4.0
      Math.floor(3.4) :3.0
      Math.floorDiv(4, 3) :1  //returns [Math.floor(4/3)].. applies to int /long
      Math.floorMod(4, 3) :1  //returns [ 4 - (floorDiv(4,3) * 4) ]
      --------------------------------------------------------------
      Math.copySign(30.34, -89.1) :-30.34   //returns 1st argument with sign of 2nd
      --------------------------------------------------------------
      Math.exp(1) :2.718281828459045   //returns Eulers number(2.7182...Math.E) raised to power of argument
      Math.expm1(1) :1.718281828459045  //returns (Math.exp(argument) -1).. so, above.. returns (2.718...-1)
      --------------------------------------------------------------
      Math.hypot(3, 4) :5.0 //returns [ sqroot (3^2 + 4^2) ]
      --------------------------------------------------------------
      Math.getExponent(3) :1
      --------------------------------------------------------------
      Math.log10(1) :0.0
      Math.log(2) : Math.log(1)      0.6931471805599453:0.0
      --------------------------------------------------------------