Java 8 - Predefined Functional Interface - Consumer

Predefined Functional Interface - Consumer
* If we no need of any return,then we will go for consumer.

interface Consumer<T>
{
public void accept(T t);
}

accept() - abstract method
andThen() - default method

Eg:
class Test
{
public static void main(String[] args)
{
Consumer<String> c=s->System.out.println(s);
c.accept("Hello");
c.accept("DURGASOFT");
}
}
Output:
Hello
DURGASOFT

Eg: Display Movie Information
class Movie
{
String name;
String hero;
String heroine;
Movie(String name,String hero,String heroine)
{
this.name=name;
this.hero=hero;
this.heroine=heroine;
}
}


class Test
{
public static void main(String[] args)
{
ArrayList<Movie> l= new ArrayList<Movie>();
populate(l);
Consumer<Movie> c= m->{
System.out.println("Movie Name:"+m.name);
System.out.println("Movie Hero:"+m.hero);
System.out.println("Movie Heroine:"+m.heroine);
System.out.println();
};
for(Movie m : l)
{
c.accept(m);
}

}
public static void populate(ArrayList<Movie> l)
{
l.add(new Movie("Bahubali","Prabhas","Anushka"));
l.add(new Movie("Rayees","Sharukh","Sunny"));
l.add(new Movie("Dangal","Ameer","Ritu"));
l.add(new Movie("Sultan","Salman","Anushka"));
}
}
Ouptut:
Movie Name:Bahubali
Movie Hero:Prabhas
Movie Heroine:Anushka

Movie Name:Rayees
Movie Hero:Sharukh
Movie Heroine:Sunny

Movie Name:Dangal
Movie Hero:Ameer
Movie Heroine:Ritu

Movie Name:Sultan
Movie Hero:Salman
Movie Heroine:Anushka

Consumer Chaining:
* To group multiple consumer
Default Methods:
* andThen()
eg:
c1.andThen(c2).andThen(c3).accept(s)


class Movie
{
String name;
String result;
Movie(String name,String result)
{
this.name=name;
this.result=result;
}
}

class Test
{
public static void main(String[] args)
{
Consumer<Movie> c1=m->System.out.println("Movie:"+m.name+" is ready to release");

Consumer<Movie> c2=m->System.out.println("Movie:"+m.name+" is just Released and it is:"+m.result);

Consumer<Movie> c3=m->System.out.println("Movie:"+m.name+" information storing in the database");

Consumer<Movie> chainedC = c1.andThen(c2).andThen(c3);

Movie m1= new Movie("Bahubali","Hit");
chainedC.accept(m1);

Movie m2= new Movie("Spider","Flop");
chainedC.accept(m2);
}
}

Output:
Movie:Bahubali is ready to release
Movie:Bahubali is just Released and it is:Hit
Movie:Bahubali information storing in the database
Movie:Spider is ready to release
Movie:Spider is just Released and it is:Flop
Movie:Spider information storing in the database

Comments

Popular posts from this blog

How to set Java Object into JaxBElement ?

GitLab