Friday, September 9, 2022

Java 8 Features with Examples

  • After java 1.5version, java 8 is the next major version.
  • Before java 8, sun people gave importance only for objects but in 1.8version oracle people gave the importance for functional aspects of programming to bring its benefits to java.ie it doesn’t mean java is functional oriented programming language.


  • Java 8 New Features:
    • 1) Lambda Expression
    • 2) FunctionalInterfaces
    • 3) Default methods
    • 4) Predicates
    • 5) Functions
    • 6) Double colon operator(::)
    • 7) Stream API
    • 8) Date and Time API

Lambda (λ) Expression

  • Lambda calculus is a big change in mathematical world which has been introducedin1930. Because of benefits of Lambda calculus slowly this concepts started using in programming world. “LISP” is the first programming which uses Lambda Expression.

  • Theother languages whichuses lambda expressionsare: 
    • C#.Net
    • C Objective C
    • C++
    • Python
    • Ruby etc.
    • and finally in java also.

  • The Main Objective of λ LambdaExpression is to bring benefits of functional programming into java.


What is Lambda Expression (λ):

  • Lambda Expression is just an anonymous(nameless) function. That means the function which doesn’t have the name,return type and access modifiers.
  • Lambda Expression also known as anonymous functions or closures.

Ex: 1:

public void m1() {
  sop(“hello”); 
}

Option 1
() -> {
   sop(“hello”); 
}

Option 2
() -> { sop(“hello”); }

Option 3
()-> sop(“hello”);

Ex: 2:

public void add(inta, int b) {
  sop(a+b);
}

Option 1
(inta, int b) -> sop(a+b);

  • If the type of the parameter can be decided by compiler automatically based on the context then we can remove types also.
  • The above Lambda expression we can rewrite as (a,b) -> sop (a+b);

Ex: 3:

public String str(String str) {

  return str; 

}

Option 1
(String str) -> return str; 

Option 2
(str) -> str;

Conclusions:

  • A lambda expression can have zero or more number of parameters(arguments).
  • Example:
    • () -> sop(“hello”);
    • (int a ) -> sop(a);
    • (inta, int b) -> return a+b;

  • Usually, we can specify type of parameter.If the compiler expect the type based on the context then we can remove the type. i.e., programmer is not required.
  • Example:
    • (inta, int b) -> sop(a+b);
    • (a,b) -> sop(a+b);

  • If multiple parameters present then these parameters should be separated with comma(,).

  • If zero number of parameters available then we have to use empty parameter [ like ()]. 
  • Example:
    • () -> sop(“hello”);

  • If only one parameter is available and if the compiler can expect the type then we can remove the ype and parenthesis also. 
  • Example:
    • (int a) -> sop(a);
    • (a)-> sop(a);
    • A -> sop(a);

  • Similar to method body lambda expression body also can contain multiple statements.if more

  • than one statements present then we have to enclose inside within curly braces.if one statement present then curly braces are optional.

  • Once we write lambda expression we can call that expression just like a method, for this functional interfaces are required.

Functional Interfaces:

  • if an interface contain only one abstract method, such type of interfaces are called functional interfaces and the method is called functional method or single abstract method(SAM).

  1. Runnable          ->  It contains only run() method
  2. Comparable      ->  It contains only compareTo() metho
  3. ActionListener   ->  It contains only actionPerformed()
  4. Callable             ->  It contains only call()method

  • Inside functional interface in addition to single Abstract method(SAM) we write any number of default and static methods.

Example:

interface Interf {
  public abstract void m1();
    default void m2() {
    System.out.println(“hello†);
  }
}

  • In Java 8 ,SunMicroSystem introduced @FunctionalInterface annotation to specify that the interface is FunctionalInterface.

Example:

@FunctionalInterface
 Interface Interf { 
       public void m1();  -> This code compiles without any compilation errors.
}

  • InsideFunctionalInterface we can take only one abstract method,if we take more than one abstract method then compiler raise an error message that is called we will get compilation error.

Example:

@FunctionalInterface {
  public void m1();  
  public void m2();    -> this code gives compilation error.
}

  • Inside FunctionalInterface we have to take exactly only one abstract method.If we are not declaring that abstract method then compiler gives an error message.

Functional Interface with respect to Inheritance:

  • If an interface extends FunctionalInterface and child interface doesn’t contain any abstract method then child interface is also FunctionalInterface

Example:

@FunctionalInterface
interface A {
  public void methodOne();
}

@FunctionalInterface
  Interface B extends A {
}

  • In the child interface we can define exactly same parent interface abstract method.
Example

@FunctionalInterface
interface A {
  public void methodOne();
}

@FunctionalInterface
interface B extends A {
  public void methodOne(); -> No Compile Time Error
}

  • In the child interface we can’t define any new abstract methods otherwise child interface won’t be FunctionalInterface and if we are trying to use @FunctionalInterface annotation then compiler gives an error message.

@FunctionalInterface {
interface A {
  public void methodOne(); 
}
@FunctionalInterface
interface B extends A {
  public void methodTwo(); -> Compiletime Error
}

Example :

@FunctionalInterface 
interface A {
  public void methodOne();  -> No compile time error
}
interface B extends A { -> this’s Normal interface so that code compiles without error 
  public void methodTwo();
}

  • In the above example in both parent & child interface we can write any number of default methods and there are no restrictions.Restrictions are applicable only for abstract methods.

Functional Interface Vs Lambda Expressions:

  • Once we write Lambda expressions to invoke it’s functionality, then FunctionalInterface is required. We can use FunctionalInterface reference to refer Lambda Expression.

  • Where ever FunctionalInterface concept is applicable there we can use Lambda Expressions 

  • Example 1
    • Without Lambda Expression.
    • interface Interf {
        public void methodOne() {}
        public class Demo implements Interface {
        
        public void methodOne() {
          System.out.println("method one execution");
        }
      public class Test {
        public static void main(String[] args) {
          Interfi = new Demo();
          i.methodOne();
        }
      }

    • Above code With Lambda expression.
    • interface Interf {
      public void methodOne() {}
      class Test {
        public static void main(String[] args) {
          Interfi = () -> System.out.println(“MethodOne Execution”);
          i.methodOne();
        }
       }

  • Example 2
    • Without Lambda Expression.
    • interface Interf {
        public void sum(inta,int b);
      }
      class Demo implements Interf {
        public void sum(inta,int b) {
          System.out.println(“Thesum:” +(a+b));
        }
      }
      public class Test {
        public static void main(String[] args) {
          Interfi = new Demo();
          i.sum(20,5);
        }
      }

    • Above code With Lambda Expression.
    • interface Interf {
        public void sum(inta, int b);
      }
      class Test {
        public static void main(String[] args) {
          Interfi = (a,b) -> System.out.println(“The Sum:” +(a+b));
          i.sum(5,10);
        }
      }
  • Example 3
    • Without Lambda Expressions.
    • interface Interf {
        public int square(int x);
      }
      class Demo implements Interf {
        public int square(int x) {
          return x*x; OR (int x) -> x*x
        }
      }
      class Test {
        public static void main(String[] args) {
          Interfi = new Demo();
          System.out.println(“The Square of 7 is: “ +i.square(7));
        }
      }
    • Above code with Lambda Expression.
    • interface Interf {
        public int square(int x);
      }
      class Test {
        public static void main(String[] args) {
          Interfi = x -> x*x;
          System.out.println(“The Square of 5 is:”+i.square(5));
        }
      }
  • Example 4
    • Without Lambda expression
    • class MyRunnable implements Runnable {
        public void main() {
          for(int i=0; i<10; i++) {
            System.out.println(“Child Thread”);
          }
        }
      }
      class ThreadDemo {
        public static void main(String[] args) {
          Runnable r = new myRunnable();
          Thread t = new Thread(r);
          t.start();
          for(int i=0; i<10; i++) {
            System.out.println(“Main Thread”)
          }
        }
      }
    • With Lambda expression.
    • class ThreadDemo {
       public static void main(String[] args) {
          Runnable r = () -> {
            for(int i=0; i<10; i++) {
              System.out.println(“Child Thread”);
            }
          };
       
          Thread t = new Thread(r);
          t.start();
          for(i=0; i<10; i++) {
            System.out.println(“Main Thread”);
          }
        }
       }


Anonymous inner classes vs Lambda Expressions

  • Wherever we are using anonymous inner classes there may be a chance of using Lambda expression to reduce length of the code and to resolve complexity.

Example 

  • With anonymous inner class.
class Test {
   public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {
      public void run() {
        for(int i=0; i<10; i++) {
          System.out.println("Child Thread");
        }  
      }
    });
 
  t.start();
  for(int i=0; i<10; i++)
    System.out.println("Main thread");
  }
 }

  • With Lambda expression

class Test {
 public static void main(String[] args) {
  Thread t = new Thread(() -> {
    for(int i=0; i<10; i++) {
      System.out.println("Child Thread");
    }
  });
  t.start();
  for(int i=0; i<10; i++) {
    System.out.println("Main Thread");
  }
 }
}

What are the advantages of Lambda expression?

  • We can reduce length of the codes so that readability of the code will be improved. 
  • We can resolve complexity of anonymous innerclasses.
  • We can provide Lambda expression in the place of object.
  • We can pass lambda expression as argument to methods.

Note:

  • Anonymous innerclass can extend concrete class,can extend abstract class,can implement interface with any number of methods but
  • Lambda expression can implement an interface with only singl abstract method(FunctionalInterface).
  • Hence if anonymous inner class implements functional interface in that particular case only we can replace with lambda expressions.hence wherever anonymous inner class concept is there,it may not possible to replace with Lambda expressions

  • Anonymousinnerclass!=LambdaExpression
  • In side anonymous inner class we can declare instance variables.
  • Inside anonymous inner class“this” always refers currentinnerclassobject(anonymousinner class) but not related outer class object

Example:

  • Inside lambda expression we can’t declare instance variables.
  • Whatever the variables declare inside lambda expression are simply acts as local variables
  • Within lambda expression ‘this' keyword represents current outer class object reference(thatis current enclosing class reference in which we declare lambda expression)

Example:

interface Interf {
  public void m1();
}
  
class Test {
 int x = 777;
  public void m2() {
    Interfi = ()-> {
      int x = 888;
      System.out.println(x); 888
      System.out.println(this.x); 777
    };
   i.m1();
  }
  public static void main(String[] args) {
    Test t = new Test();
    t.m2();
  }

  • From lambda expression we can access enclosing class variables and enclosing method variables directly.
  • The local variables referenced from lambda expression are implicitly final and hence wecan’t perform re-assignment for those local variables otherwise we get compile time error

Example:

interface Interf {
 public void m1();
}
class Test {
 int x = 10;
 public void m2() {
  int y = 20;
  Interfi = () -> {
    System.out.println(x); 10
    System.out.println(y); 20
     x = 888;
    y = 999; //CE
  };
 
  i.m1();
  y = 777;
 }
 public static void main(String[] args) {
  Test t = new Test();
  t.m2();
 }
}

Differences between anonymous inner classes and Lambda expression

Anonymous Inner class 

  • It’s a class without name
  • Anonymous inner class can extend Abstract and concreateclasses Anonymous inner classes can be Instantiated
  • Anonymous inner class can implement An interface that contains any number of Abstract methods
  • Inside anonymous inner class we can Declare instance variables.
  • Anonymous inner classes can be Instantiated
  • Inside anonymous inner class “this” Always refers current anonymous Inner class object but not outer class Object.
  • Anonymous inner class is the best choice If we want to handle multiple methods.
  • In the case of anonymous inner class At the time of compilation a separate Dot class file will be generated (outerclass$1.class)
  • Memory allocated on demand Whenever we are creating an object

Lambda Expression

  • It’s a method without name(anonymous function)
  • lambda expression can’t extend Abstract and concreate classes
  • lambda expression can implement an Interface which contains single abstract method (FunctionalInterface)
  • Inside lambda expression we can’t Declare instance variables,whater the variables declare are simply acts as local variables.
  • lambda expressions can’t be instantiated
  • Inside lambda expression “this” Always refers current outer class object.that is enclosing class object.
  • Lambda expression is the best Choice if we want to handle interface With single abstract method (FuntionalInterface).
  • At the time of compilation no dot Class file will be generated for Lambda expression.it simply convert in to private method outer class.
  • Reside in permanent memory of JVM (Method Area).

Default methods

  • Until1.7 version on wards inside interface we can take only public abstract methods and public static final variables(every method present inside interface is always public and abstract whether we are declaring or not).
  • Every variable declared inside interface is always public static final whether we are declaringor not.
  • But from 1.8 version onwards in addition to these, we can declare default concrete methods also inside interface,which are also known as defender methods.
  • We can declare default method with the keyword “default” as follows.

  • default void m1(){
      System.out.println (“Default Method”);
    }

  • Interface default methods are by-default available to all implementation classes.Based on requirement implementation class can use these default methods directly or can override.

Example 

  • interface Interf {
      default void m1() {
        System.out.println("Default Method");
      }
    }
    class Test implements Interf {
      public static void main(String[] args) {
        Test t = new Test();
        t.m1();
      }
    }

  • Default methods also known as defender methods or virtual extension methods.
  • The main advantage of default methods is without effecting implementation classes we can addnew functionality to the interface(backward compatibility).

Note:

  • We can’t override object class methods as default methods inside interface otherwise we get compiletime error.

Example:

  • interface Interf {
      default inthashCode() {
        return 10;
      }
    }

  • Output
            CompileTimeError

Reason: 

  • Object class methods are by-default available to every java class hence it’s not required to bring through default methods.


Default method vs multiple inheritance

  • Two interfaces can contain default method with same signature then there may be a chance of ambiguity problem(diamond problem) to the implementation class.to overcome this problem compulsory we should override default method in the implementation class otherwise we get compiletime error.

Example 1:

interface Left {
  default void m1() {
    System.out.println("Left Default Method");
  }
 }

 Example 2:

interface Right {
  default void m1() {
    System.out.println("Right Default Method");
  }
 }

 Example 3:

 class Test implements Left, Right {}

How to override default method in the implementation class?

  • In the implementation class we can provide complete new implementation or we can call any interface method as follows.
  • interfacename.super.m1(); 

Example:

class Test implements Left, Right {
  public void m1() {
    System.out.println("Test Class Method"); OR Left.super.m1();
  }
 
  public static void main(String[] args) {
    Test t = new Test();
    t.m1();
  }
}

Differences between interface with default methods and abstract class

  • Eventhough we can add concrete methods in the form of default methods to the interface , it wont be equal to abstract class.

Interface with Default Methods

  • Inside interface every variable is Always public static final and there is No chance of instance variables
  • Interface never talks about state of Object.
  • Inside interface we can’t declare Constructors.
  • Inside interface we can’t declare Instance and static blocks.
  • Functional interface with default Methods Can refer lambda expression.
  • Inside interface we can’t override Object class methods.

Abstract Class

  • Inside abstract class there may be a Chance of instance variables which Are required to the child class.
  • Abstract class can talk about state of Object.
  • Inside abstract class we can declare Constructors.
  • Inside abstract class we can declare Instance and static blocks.
  • Abstract class can’t refer lambda Expressions.
  • Inside abstract class we can override Object class methods.


Static methods inside interface:

  • From 1.8version onwards in addition to default methods we can write static methods also inside interface to define utility functions.
  • Interface static methods by-default not available to the implementation classes hence by using implementation class reference we can’t call interface static methods.we should call interface static methods by using interface name.

Example:

interface Interf {
  public static void sum(int a, int b) {
    System.out.println("The Sum:"+(a+b));
  }
}
class Test implements Interf {
  public static void main(String[] args) {
    Test t = new Test();
    t.sum(10,; //CE
    Test.sum(10,; //CE
    Interf.sum(10,;
  }
}

  • As interface static methods by default not available to the implementation class,overriding concept is not applicable.
  • Based on our requirement we can define exactly same method in the implementation class,it’s valid but not overriding.


Example1:

interface Interf {
  public static void m1() {}
}
class Test implements Interf {
  public static void m1() {}
}

It’s valid but not overriding

Example 2:

interface Interf {
  public static void m1() {}
}
class Test implements Interf {
  public void m1() {}
}

This’s valid but not overriding

Example 3:

class P {
  private void m1() {}
}
class C extends P {
  public void m1() {}
}
This’s valid but not overriding

  • From 1.8 version onwards we can write main()method inside interface andhence we can run interface directly from the command prompt.

Example 4:

interface Interf {
  public static void main(String[] args) {
    System.out.println("Interface Main Method");
  }
}

Output

    At the command prompt: 
    javac Interf.java 
    javaInterf
Predicates

  • A predicate is a function with a single argument and returns boolean value.
  • To implement predicate functions injava,oracle people introduced Predicate interface in 1.8 version(i.e.,Predicate<T>).
  • Predicate interface present in java.util.function package.
  • It’s a functional interface and it contains only one method i.e., test()

Example:

interface Predicate<T> {
  public boolean test(T t); 
}

  • As predicate is a functional interface and hence it can refers lambda expression

Example:1

Write a predicate to check whether the given integer is greater than 10 or not.

public boolean test(Integer I) {
  if (I >10) {
    return true;
  } else {
    return false; 
  }
}
      
      ||
     \  /

(Integer I) -> { 
  if(I > 10)
    return true;
  else
  return false;
}

      ||
     \  /
      
I -> (I>10);

      ||
     \  /
  
predicate<Integer> p = I ->   (I >10); 
System.out.println (p.test(100)); true 
System.out.println (p.test(7)); false

Program:

import java.util.function;             
 class Test {
  public static void main(String[] args) {
    predicate<Integer> p = I -> (i>10);
    System.out.println(p.test(100));
    System.out.println(p.test(7));
    System.out.println(p.test(true)); //CE
  }
 }

# 1 Write a predicate to check the length of given string is greater than 3 or not. 

  Predicate<String> p = s -> (s.length() >;
  System.out.println (p.test(“rvkb”)); true
  System.out.println (p.test(“rk”)); false

#-2 write a predicate to check whether the given collection is empty or not. Predicate<collection> p = c -> c.isEmpty();


Predicate joining

  • It’s possible to join predicates into a single predicate by using the following methods. 
               and() 
               or() 
               negate()
      these are exactly same as logical AND ,OR complement operators


Example:

import java.util.function.*;
class test {
 public static void main(string[] args) {
  int[] x = {0, 5, 10, 15, 20, 25, 30};
  predicate<integer> p1 = i->i>10;
  
  predicate<integer> p2=i -> i%2==0;
  System.out.println("The Numbers Greater Than 10:");
  m1(p1, x);
  
  System.out.println("The Even Numbers Are:");
  m1(p2, x);
  System.out.println("The Numbers Not Greater Than 10:");             
  
  m1(p1.negate(), x);
  System.out.println("The Numbers Greater Than 10 And Even Are:†);
 
  m1(p1.and(p2), x);
  System.out.println("TheNumbersGreaterThan10OREven:†);
 
  m1(p1.or(p2), x);
 }
 public static void m1(predicate<integer>p, int[] x) {
  for(int x1:x) {
    if(p.test(x1))
    System.out.println(x1);
  }
 }
}

Function

  • Functions are exactly same as predicates except that functions can return any type of result but function should(can)return only one value and that value can be any type as per our requirement. 
  • To implement functions oracle people introduced Function interface in 1.8version.
  • Function interface present in java.util.function package.
  • Functional interface contains only one method i.e., apply().

interface function(T,R) { 
  public R apply(T t);
}

Example :- Write a function to find length of given input string.

import java.util.function.*;
class Test {
  public static void main(String[] args) {
    Function<String, Integer> f = s ->s.length();
    System.out.println(f.apply("cloud"));
    System.out.println(f.apply("tech"));
  }
}

Note:

  •   Function is a functional interface and hence it can refer lambda expression.


Differenece between predicate and function

Predicate

  • To implement conditional checks We should go for predicate
  • Predicate can take one type Parameter which represents Input argument type. Predicate<T>
  • Predicate interface defines only one method called test()
  • publicboolean test(T t)
  • Predicate can return only boolean value.

Function

  • To perform certain operation And to return some result we Should go for function.
  • Function can take 2 type Parameters.first one represent Input argument type and Second one represent return Type.
  • Function<T,R>
  • Function interface defines only one Method called apply().
  • public R apply(T t)
  • Function can return any type of value

Note:

  • Predicate is a boolean valued function and(), or(), negate() are default methods present inside Predicate interface.


Method and Constructor references by using ::(double colon)operator

  • Functional Interface method can be mapped to our specified method by using :: (double colon)operator. This is called method reference.
  • Our specified method can be either static method or instance method.
  • Functional Interface method and our specified method should have same argument types ,except this the remaining things 
  • returntype,methodname,modifiersetc are not required to match.

Syntax:

  • if our specified method is static method 

Classname::methodName

  •   if the method is instance method 

Objref::methodName

  • FunctionalInterface can refer lambda expression and FunctionalInterface can also refer method reference . Hence lambda expression can be replaced with method reference.
  • hence method reference is alternative syntax to lambda expression.

Example: 

  • With Lambda Expression.

class Test {
 public static void main(String[] args) {
   Runnable r = () -> {
    for(int i=0; i<=10; i++) {
       System.out.println("Child Thread");
    }
  };
 
  Thread t = new Thread(r);
  t.start();
 
  for(int i=0; i<=10; i++) {
    System.out.println("Main Thread");
  }
 }
}

  • With Method Reference

class Test {
 public static void m1() {        
  for(int i=0; i<=10; i++) {
    System.out.println("Child Thread");
  }
 }
 
 public static void main(String[] args) {
  Runnable r = Test:: m1;
  Thread t = new Thread(r);
  t.start();
  
  for(int i=0; i<=10; i++) {
    System.out.println("Main Thread");
 }
}

  • In the above example Runnable interface run() method referring to Test class static method m1(). Method reference to Instance method:

Example:

interface Interf {
  public void m1(int i);
}
class Test {
 public void m2(int i) {
   System.out.println("From Method Reference:"+i);
 }
 
 public static void main(String[] args) {
   Interf f = I ->sop("From Lambda Expression:"+i);
   f.m1(10);
 
   Test t = new Test();
   Interf i1 = t::m2;
   i1.m1(20);
 }
}

  • In the above example functional interface method m1() referring to Test class instance method m2(). The main advantage of method reference is we can use already existing code to implement functional interfaces(code reusability).

Constructor References

  • We can use :: ( double colon )operator to refer constructors also

Syntax: classname :: new

Example 1:

  Interf f = sample :: new;
  functional interface f referring sample class constructor
Example 2: 
class Sample {
 private String s;
 Sample(String s) {
  this.s = s;
  System.out.println("Constructor Executed:"+s);
 }
}
interface Interf {
 public Sample get(String s);
}
class Test {
 public static void main(String[] args) {
  Interf f = s -> new Sample(s);
  f.get("From Lambda Expression");
  Interf f1 = Sample :: new;
  f1.get("From Constructor Reference");
 }
}

Note:

  • In method and constructor references compulsory the argument types must be matched.

Streams

  • To process objects of the collection, in 1.8 version Streams concept introduced.


What is the differences between java.util.streams and java.io streams?

  • java.util streams meant for processing objects from the collection. Ie, it represents a stream of objects from the collection but java.io streams meant for processing binary and character data with respect to file. i.e it represents stream of binary data or character data from the file .hence java.io streams and java.util streams both are different.


What is the difference between collection and stream?

  • if we want to represent a group of individual objects as a single entity then we should go for collection.
  • if we want to process a group of objects from the collection then we should go for streams.

Method

  • we can create a stream object to the collection by using stream()method of Collection interface. stream() method is a default method added to the Collection in 1.8 version.
  • default Stream stream()

Example:
Stream s = c.stream();

  • Stream is an interface present in java.util.stream. once we got the stream, by using that we can process objects of that collection.
  • we can process the objects in the following two phases
    • 1.configuration 
    • 2.processing

1.Configuration:

  • we can configure either by using filter mechanism or by using map mechanism.

Filtering:

  • we can configure a filter to filter elements from the collection based on some boolean condition by using filter()method of Stream interface.
  • public Stream filter(Predicate<T> t) here (Predicate<T > t ) can be a boolean valued function/lambda expression 

  •   Stream s=c.stream();
      Stream s1=s.filter(i -> i%2==0);

  • Hence to filter elements of collection based on some booleancondition we should go for filter()method.

Mapping:

  • If we want to create a separate new object, for every object present in the collection based on our requirement then we should go for map () method of Stream interface.
  • public Stream map (Function f); -> It can be lambda expression also
  • Example

  • Stream s = c.stream();
    Stream s1 = s.map(i-> i+10);

  • Once we performed configuration we can process objects by using several methods.


2.Processing

  • processing by collect() method 
  • Processing by count()method 
  • Processing by sorted()method 
  • Processing by min() and max() methods 
  • forEach() method
  • toArray() method Stream.of()method

processing by collect() method

  • This method collects the elements from the stream and adding to the specified to the collection indicated (specified)by argument.

  • Example -: To collect only even numbers from the array list
    • Approach-1: without Streams:
      import java.util.*;
      class Test {
       public static void main(String[] args) {
        ArrayList<Integer> l1 = new ArrayList<Integer>();
        for(int i=0; i<=10; i++) {
          l1.add(i);
        }
        System.out.println(l1);
       
        ArrayList<Integer> l2 = new ArrayList<Integer>();
        for(Integer i:l1) {
          if(i%2 == 0)
            l2.add(i);
          }
          System.out.println(l2);
        }
       }
      }
    • Approach-2: With Streams:
      import java.util.*;
      import java.util.stream.*;
      class Test {
       public static void main(String[] args) {
         ArrayList<Integer> l1 = new ArrayList<Integer>();
          for(inti=0; i<=10; i++) {
            l1.add(i);
          }
          System.out.println(l1);
       
          List<Integer> l2 = l1.stream().filter(i -> i%2==0).collect(Collectors.toList());
          System.out.println(l2);
       }
      }

  • Program for map() and collect() Method:
    import java.util.*;
    import java.util.stream.*;
    class Test {
     public static void main(String[] args) {
      ArrayList<String> l = new ArrayList<String>();
      l.add("rvk"); 
      l.add("rk"); 
      l.add("rkv"); 
      l.add("rvki"); 
      l.add("rvkir");
      System.out.println(l);
      List<String> l2 = l.Stream().map(s ->s.toUpperCase())
        .collect(Collectors.toList());
      System.out.println(l2);
     }
    }

Processing by count()method

  • This method returns number of elements present in the stream.

Method 

  • public long count()

Example:

 long count=l.stream().filter(s ->s.length()==5).count(); 
  sop(“the number of 5 length strings is:”+count);

Processing by sorted()method

  • if we sort the elements present inside stream then we should go for sorted() method. the sorting can either default natural sorting order or customized sorting order specified by comparator.

  • sorted()- default natural sorting order
  • sorted(Comparator c)-customized sorting order.

  • Example

  • List<String> l3=l.stream().sorted().collect(Collectors.toList()); 
    sop(“according to default natural sorting order:”+l3);

    List<String> l4=l.stream()
      .sorted((s1,s2) -> -s1.compareTo(s2))
        .collect(Collectors.toList()); 

    sop(“according to customized sorting order:”+l4);

Processing by min() and max() methods

  • min(Comparator c) -> mreturns minimum value according to specified comparator.
  • max(Comparator c) -> returns maximum value according to specified comparator

  • Example:

      String min=l.stream().min((s1,s2) -> s1.compareTo(s2)).get(); 
      sop(“minimum value is:”+min);
     
     String max=l.stream().max((s1,s2) -> s1.compareTo(s2)).get(); 
     sop(“maximum value is:”+max);

forEach() method

  • this method will not return anything.
  • this method will take lambda expression as argument and apply that lambda expression for each element present in the stream.
  • Example 1:
  •   l.stream().forEach(s->sop(s));
      l3.stream().forEach(System.out:: println);
  • Example 2
  • import java.util.*;
    import java.util.stream.*;
    class Test1 {
      public static void main(String[] args) {
        ArrayList<Integer> l1 = new ArrayaList<Integer>();
        l1.add(0); 
        l1.add(15); 
        l1.add(10); 
        l1.add(5); 
        l1.add(30); 
        l1.add(25); 
        l1.add(20);
        System.out.println(l1);
        ArrayList<Integer> l2=l1.stream().map(i-> i+10).collect(Collectors.toList());  
        System.out.println(l2);
       
       long count = l1.stream().filter(i->i%2==0).count();
       System.out.println(count);
     
       List<Integer> l3=l1.stream().sorted().collect(Collectors.toList());
       System.out.println(l3);
     
       Comparator<Integer> comp=(i1,i2)->i1.compareTo(i2);
       List<Integer> l4=l1.stream().sorted(comp).collect(Collectors.toList());
       System.out.println(l4);
       
       Integer min=l1.stream().min(comp).get();
       System.out.println(min);
       
       Integer max=l1.stream().max(comp).get();
       System.out.println(max);
       l3.stream().forEach(i->sop(i));
       l3.stream().forEach(System.out:: println);
     }
    }

toArray() method

  • we can use toArray() method to copy elements present in the stream into specified array

  • Example:

  • Integer[] ir = l1.stream().toArray(Integer[] :: new); 
    for(Integer i: ir) {
      sop(i); 
    }

Stream.of()method

  •  We can also apply a stream for group of values and for arrays.

  • Example:

  •  Stream s=Stream.of(99,999,9999,99999); 
     s.forEach(System.out:: println);
      
      Double[] d={10.0,10.1,10.2,10.3};
      Stream s1=Stream.of(d);
      s1.forEach(System.out :: println);


Date and Time API: (Joda-Time API)

  • until java 1.7version the classes present in java.util package to handle Date and Time(like Date,Calendar,TimeZoneetc) are not upto the mark with respect to convenience and performance.
  • To overcome this problem in the 1.8version oracle people introduced Joda-Time API . This API developed by joda.org and available in java in the form of java.time package.

Program for to display System Date and time.

import java.time.*;
public class DateTime {
 public static void main(String[] args) {
    LocalDate date = LocalDate.now();
    System.out.println(date);
    
    LocalTime time=LocalTime.now();
    System.out.println(time);
 }
}

Output: 

2015-11-23 
12:39:26:587

  • Once we get LocalDate object we can call the following methods on that object to retrieve Day,month and year values separately.

Example 1:

import java.time.*;
class Test {
 public static void main(String[] args) {
  LocalDate date = LocalDate.now();
  System.out.println(date);
  
  int dd = date.getDayOfMonth();
  int mm = date.getMonthValue();        
  int yy = date.getYear();
 
  System.out.println(dd+"..."+mm+"..."+yy);
  System.out.printf("\n%d-%d-%d",dd,mm,yy);
 }
}

  • Once we get LocalTime object we can call the following methods on that object. 

Example 2:

import java.time.*;
class Test {
  public static void main(String[] args) {
    LocalTime time = LocalTime.now();
    int h = time.getHour();
    int m = time.getMinute();
    int s = time.getSecond();
    int n = time.getNano();
    System.out.printf("\n%d:%d:%d:%d",h,m,s,n);
  }
}

  • If we want to represent both Date and Time then we should go for LocalDateTime object.
  • LocalDateTimedt = LocalDateTime.now(); System.out.println(dt);

    • O/p:2015-11-23T12:57:24.531

  • We can represent a particular Date and Time by using LocalDateTime object as follows.

Example:

LocalDateTime dt1=LocalDateTime.of(1995,Month.APRIL,28,12,45);
sop(dt1);

Example:

LocalDateTime dt1=LocalDateTime.of(1995,04,28,12,45); sop(dt1);
Sop(“After six months:”+dt.plusMonths(6)); 
Sop(“Before six months:”+dt.minusMonths(6));

To Represent Zone: ZoneId object can be used to represent Zone.

Example:

import java.time.*;
class ProgramOne {           
 public static void main(String[] args) {
  ZoneId zone = ZoneId.systemDefault();
  System.out.println(zone);
 }
}

We can create ZoneId for a particular zone as follows 

Example:

 ZoneId la = ZoneId.of("America/Los_Angeles"); 
 ZonedDateTimezt = ZonedDateTime.now(la); 
 System.out.println(zt);

Period Object: Period object can be used to represent quantity of time

Example:

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1989,06,15);

Period p = Period.between(birthday,today);

System.out.printf("age is %d year %d months 
  %d days",p.getYears(),p.getMonths(),p.getDays());

 Write a program to check the given year is leap year or not.:

import java.time.*;
public class Leapyear {
 int n = Integer.parseInt(args[0]);
 Year y = Year.of(n);
 
 if(y.isLeap())
  System.out.printf("%d is Leap year",n);
 else
  System.out.printf("%d is not Leap year",n);
}


You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS