lamda and anonymous inner classes

Anonymous inner classes

Anonymous inner classes in their daily programming is often used. such as

ArrayList<String> list=new ArrayList<>();
list.add(new String("Hello World!"));

lamda is a new feature java 8. Java8 with the process stream flow, particularly convenient

//list.foreach
ArrayList<String> list=new ArrayList<>();
list.add("Hello");
list.add("World");
list.foreach(o->{
    System.out.println(o);
});
//stream
list.stream().foreach(o->{
    System.out.println(o);
});

There is also a function of java interfaces, in the preparation of the lamda will use to represent such a simple thing

  • Function
  • Consumer
  • Predicate
  • Supplier
    these common function interface has a lot of use in stream flow, it is still very useful.

Personal feeling

I feel lamda approximately equal to an anonymous inner class. The difference lies.
Anonymous inner class is a class, have all the characteristics of the class, such as on private property, you can override the method or something.
lamda is the interface, it is necessary to rewrite the inheritance, and no private variables, final still be there, lamda required function interface has only one method, if there are multiple, the other must be default

Guess you like

Origin www.cnblogs.com/duangL/p/11610444.html