Great Deals

Showing posts with label java8. Show all posts

Stream() Java8

Hi Guys,
We will have a look at powerful functionality in java8.

Stream vs Collection

Streams:
Takes advantage of declarative programming it gives hint about what operations need to perform on source.

Collection:
It has direct access on source (array, collections).
You will need to take care of iteration.

What is Stream?
Stream is composed of the Stream pipeline.

Stream=Source+Intermediary Operation+Terminal Operations

Source which may be array, collection.

Intermediary operations such as filter to collect results that satisfy some predicate.

Terminal operations:sum,avg,count
Computations are performed at this stage.

Facts about Streams
1.     Streams can’t be reused.
2.     No need to close the streams they are autoclosable.
3.     However the streams related to IOChannel(File) must be closed

Example on Streams
package com.seetest;

import java.util.ArrayList;
import java.util.List;
public class HelloWorld{

     public static void main(String []args){
        List<String> phones=new ArrayList<String>();
        phones.add("samsung");
        phones.add("xiomi");
        phones.stream().filter(s->s.startsWith("s")).forEach(System.out::println);
        //String phone;
      
    
     }
}

            Methods in Stream Class:
   
1.     findAny
2.     findFirst
3.     limit
4.     min
5.     map()
6.     mapToInt()
7.     mapToDouble()




1.findAny:
Returns any element in the stream.
import java.util.ArrayList;
import java.util.List;
public class HelloWorld{

     public static void main(String []args){
        List<String> phones=new ArrayList<String>();
        phones.add("samsung");
        phones.add("xiomi");
        phones.stream().findAny().ifPresent(System.out::println);
        //String phone;
      
    
     }
}


2.findFirst:

findFirst returns the first elements of the stream

import java.util.ArrayList;
import java.util.List;
public class HelloWorld{

     public static void main(String []args){
        List<String> phones=new ArrayList<String>();
        phones.add("samsung");
        phones.add("xiomi");
        phones.stream().findFirst().ifPresent(System.out::println);
        //String phone;
      
    
     }
}

3.limit:
limits how many rows should be shown.

import java.util.ArrayList;
import java.util.List;
public class HelloWorld{

     public static void main(String []args){
        List<String> phones=new ArrayList<String>();
        phones.add("samsung");
        phones.add("xiomi");
        phones.stream().limit(1).forEach(System.out::println);
        //String phone;
      
    
     }
}


4.min-
To find the minimum element in the system.
For this we need to implement the comparator
Signature: min() takes comparator
(s1,s2)->{return         s1.compareTo(s2);}

import java.util.ArrayList;
import java.util.List;
public class HelloWorld{

     public static void main(String []args){
        List<String> phones=new ArrayList<String>();
        phones.add("xiomi");
        phones.add("Samsung");
        phones.stream().min((s1,s2)->{return         s1.compareTo(s2);}).ifPresent(s->System.out.println(s));
     }
 }




java8 lambda




What is lambda Expressions?


                  The lambda expression is just like the function it consist of


  • List of parameters
  • Method Body
  • return Type


Lambda Expression termed as anonymous because it does not have any name.
Lambda Expression passed as arguments to the methods.


Anatomy of Lambda expression :)

Yes guys you heard it right we are going to do the dissection of the Lambda Expression.

Lambda expression=Parameters+Arrow+Method Body

(Car c1,Car 2)   ->      c1.getPrice().comparTo(c2.getPrice());

Please have a look at the below code snippets where i have compared codes of Java7 and Java8

Example 1
Using Java7

Comparator<Car> byPrice=new Comparator<Car>(){

Public int compare(Car c1,Car c2){

    return c1.getPrice().compareTo(c2.getPrice());

}

};

By Lambda Expressions
Using Java8


Comparator<Car> byPrice=(Car c1,Car c2)--->c1.getPrice().compareTo(c2.getPrice());

Example 2

Java7
class A implements Runnable
{
       public void run()
     {
                System.out.println("I am Java7");
      }
}

By Lambda Expression
Java8

()->{System.out.println("I am Java8");}


Advantage of Lambda Interface:

Cleaner Code:Lambdas are your code much easier to read.


Convert Java Object List to Json Array


Code for demonstrating the Conversion of Java Object to Json Array

Jars Required:

  • http://central.maven.org/maven2/com/google/code/gson/gson/2.3.1/gson-2.3.1.jar<br/>
  • http://repo.grails.org/grails/repo/org/immutables/gson/2.1.0.alpha/gson-2.1.0.alpha.jar


import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.model.Product;
import com.google.gson.reflect.TypeToken;
/**
 * Servlet implementation class UserController
 */
@WebServlet("/users")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserController() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products=new ArrayList<Product>();
products.add(new Product(1, "Pen", "Smooth Pencil", 23));
com.google.gson.Gson gsonObj=new Gson();
Type listTypes=new TypeToken<List<Product>>(){}.getType();
//;
PrintWriter pw=response.getWriter();
pw.write(gsonObj.toJson(products,listTypes));
pw.close();
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

Advertising