Great Deals

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 Part2 Streams

Java8 Streams
The Java conventional style to deal with collection is external iteration.
We deal with collection by
  • Internal iteration
  • External iteration
The term external iteration implies you need to explicitly take care of iteration of elements in collection then validate each element and add it to the other list.

Where as internal iteration implies.
Java8 itself gives capability to iterate each and every element you just need to supply filter criteria.
 
For internal iteration it comes with three important methods to deal with collection of objects.
 
1.Map
2.Filter
3.Reduce


1.Map:
  • Map method allows you to process one by one element of collection.
  • Takes argument as lambda expression
  • apply lambda expression on every element
  • Return results.

Map generates each processed element in the seperate streams
FlatMap: whereas flatmap each processed element flattened into the seperate stream.

2.Filter
Produces a new Stream that contains only the elements of the original Stream that pass a given test.

3.Reduce
  • Reductions operation occurs at the end of the all operations.
  • Hence it is also termed as terminal operation.
Generally the methods used for reductions are
1. Sum
2..Average
3. Count
4. toArray


Different kinds of streams
1.Stream
2. Parellal Stream-

1.Stream
Allows you to convert List into Stream Objects
Method :listObj.strean()
 
2.Parallel Stream
You can do operate on your stream in parallel.
When you call parallelStream() it creates several threads and operates on our collection simultaneously.

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.


Persistence LIife Cycle

There are in all four stages of Object in hibernate

1.Transient
2.Persistent
3.Removed
4.Detached

HIbernate life cycle.PNG
1.Transient Objects

When an object is instantiated it's not persistent immediately let's suppose we are creating simple object if I am having in Employee class.
We will create instance in this way,

Employee emp= new employee();

When we create object it is in  transient state.
Once scope of the method where object is created finishes object will be garbage collected.

2.Persistent Objects

So in order to save such kind of objects Hibernate Persistence came in picture so the persistent manager allows us to save such kind of objects with the help of save method.

session.save(emp);
session.update(emp);

Persistent system manager will save the object having valid database entry and with valid primary key identifier.we create while declaring entity.
We Declare Primary key and entity using these ways.

XML

<hibernate-mapping>
<class name="pojo1" table="pojo1" discriminator-value="s">
<id name="empid" type="string" >
 <generator class="assigned"/>
</hibernate-mapping>

Hibernate

@javax.persistence.Id before the appropriate field in POJO with @Column
@Entity
Class Employee implements Serializable
@Id
@Column(name="user_id")
Private String userId

When I am going to save object with the help of hibernate session.You can save this object at this stage.Peristent instance are always associated with persistence context. If you want to save your changed records then you can set dynamic update=true that means once you changing some column values it will be updated automatically.

3.Removed Object

You can delete in entity instance by removing all the references on the object it will go to the remove state. Persistence manager signals that this object is in removes state and it is been scheduled for deletion at the end of the transaction so the remove object should not be used again for any course because it won't be available as soon as the operation completes so you need to discard any kind of references you are holding for such kind of object.

4.Detached Object

Detached object is the one which is in initial stage is transient So now to save the transient object what we do we call persistent manage’s save or update method that will make an object is persistence and as long as we are in the persistence context that object is supposed to be in persistent stage.

Now imagine you're closing this persistence context so once the work is done persistence context is closed but we are still having the handle to that reference so what we supposed to do with the reference now because we are done.The object whose  reference you are holding now is no longer guaranteed to be synchronised with the database so it is no longer attached to persistence context.

You can work on the detached object can modify it you can do when you place in with it now the one thing you can do if you want to save the modification.

You can perform two operations
1.Reattach
2.Merge

However Java persistence allows you or recommends you to do merging so merging implies The ability to take object from persistence context to the presentation layer and later reuse them in a new persistence context is advantage of JPA.
If you really like this tutorial please Share this tutorial.

Cool Gadgets



Filter in AngularJs


<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>

var app=angular.module('myApp',[]);
app.controller('ct',function($scope){
$scope.arr=["Shiv","Jagan"];
});
</script>
</head>
<body>
<div ng-app="myApp" id="u" ng-controller="ct">
Name<input type="text" ng-model="userName"/>
<ul>
<li ng-repeat="x in arr|filter:userName">
User Name:{{x}}
</ul>

</div>

Exception Handling puzzle


Hi please pay close attention to this small code snippette.
As our rule says exception handling mechanism
The finally block always gets executed even if we are using the return statements.

The code will return the OP as 30

public class TryCatchDemo {
static int giveInt()
{
     try
     {
           return 10;
     }
     catch(Exception e)
     {
           return 20;
     }
     finally
     {
           return 30;
     }
    
     }
     public static void main(String[] args) {
     System.out.println(""+giveInt());

     }

}



StringBuilder Demo




public class StringBuilderDemo {

     public static void main(String[] args) {
            StringBuilder sb = new StringBuilder("Shiv");
          
               System.out.println("Original String " + sb);
            
               System.out.println("substring: " + sb.substring(0,2));
          
 //  StringBuilder java.lang.StringBuilder.replace(int start, int end, String str)
               sb = sb.replace(4,4,"!!!!");
               System.out.println("replace String from location 4 to 4 charecters from location 4  " + sb);
            
               System.out.println("indexOf() charecter S is   " + sb.indexOf("S"));
            
    //Syntax StringBuilder java.lang.StringBuilder.insert(int offset, String str)
               sb = sb.insert(5, "is");
               System.out.println("inserted String  " + sb);
              
              //Syntax StringBuilder java.lang.StringBuilder.append(String str)
               sb = sb.append(" lord");
               System.out.println("append: " + sb);
          
               System.out.println("lastIndexOf charecter i is  " + sb.lastIndexOf("i"));
               sb = sb.reverse();
               System.out.println("reverse: " + sb);
     }

}



String Demo


public class StringDemo {

       public static void main(String[] args) {
       String s=new String("Shiv");
      
       char firstChar=s.charAt(0);
       System.out.println("First Charecter"+firstChar);
      
       boolean status=s.contains("i");
       if(status){
              System.out.println("i Found");
       }else{
              System.out.println("i Not Found");
       }

       status=s.endsWith("iv");
       if(status){
              System.out.println("ends with iv");
       }else{
              System.out.println(" Not ends with iv");
       }

       String newString=s.replace('v', 'V');
                     System.out.println("Replaced= "+newString);
      
       String name="Ajju";
       System.out.println("Last Occurance of J= "+name.lastIndexOf("j"));
       System.out.println("First Occurance of J= "+name.indexOf("j"));
       //**Substring starting from point 2*/
       System.out.println("SubString"+name.substring(2));
      
       name="Java is Great";
      
       String []words=name.split(" ");
      
       for(String oneWord:words)
       {
              System.out.println(""+oneWord);
       }
      
       }
      
      
}



Advertising