Java is a language multiple platform that used by the most developers.
After java 8 oracle add a lot of features to java like lambda
All know anonymous class that we can implement method of class in time executing time
Lambda is just anonymous class that implement a one method of interface
Lambda syntax
// first
l = ()->{ statements };
// second
l = (arg,arg2,arg3,...args)->{ statements };
// third
l = (n)->n; is like (n)->{ return n;};
*** Lambda rules ***
- lambda implement just a one interface and interface most have a one method
- lambda can take 0,* args
- lambda can be implement anywhere
- lambda can be return by any method
- lambda can not be returning by itself
- lambda can be passed as args
** Let begin with simple example **
interface says {
public void show();
}
public class Lambda {
public static void main(String[] args) {
says msg = ()->{ System.out.println("hello world");};
msg.show(); // hello world
}
}
Lambda example with args
interface says {
public void show(String name);
}
public class Lambda {
public static void main(String[] args) {
says msg = (name)->{ System.out.println("hello world "+ name );};
msg.show("jamal"); // hello world jamal
}
}
** Lambda with return by another method **
interface says {
public void show(String name);
}
public class Lambda {
public static says m(String msg){
return (name)->{ System.out.println(msg+" "+name);};
}
public static void main(String[] args) {
m("hello world").show("jamal");
m("hello world").show("mohammed");
}
}
** passing Lambda as arg of a method **
interface says {
public void show(String name);
}
public class Lambda {
public static void m(says l,String name){
l.show(name);
}
public static void main(String[] args) {
m((name)->{
System.out.println(name);
},"hello");
m((name)->{
for (int i=0;i<name.length();i++) {
System.out.println(name.charAt(i));
}
},"hello world");
}
}
the last example is most used in practice
Java had do a effort to integrate lambda but it's just anonymous class ,
while JavaScript has arrow function that very easy to use
Top comments (0)