Java  8 Lambdas Vs Anonymous Classes

Java 8 Lambdas Vs Anonymous Classes

well we can write lambda expression 

  • To replace the anonymous inner class.
  • Lambda expression make code very neat and clean.
  • Lambda expression are very to read. So, they make code more readable.

So the reason to opt for lambdas is just because concise code, more readability, less ceremony to do simple things i.e. replacement of anonymous class (you still have to write an anonymous class, in case of lambda you don't have to write a class). Reuse of code, create lambda expressions and pass it around methods. Further more introduction of lambda enabled number of good things in API such as Stream which provides an abstraction over the iteration. 

In Java 1.7 there was a new JVM Opcode was released named invokedynamic and Java 8 Lambda uses this. So if you have 10 anonymous classes that is 10 more classes in the final jar.

Lets first see the below example that simply uses anonymous java class - Pre Java 8

so below two class files have been created after compliation..

Now below the above program is been coded as per Java 8 standard that also include Lambdas and finally we get the rid from anonymous classes also .

With Lambdas only one class file is created as shown below


So below is another example ..

e



Raja Anbazhagan

Sr DevOps Engineer| DevOps Specialist Java, Spring-Boot, Play-Framework, Jenkins, Gitlab-CI, Github-Actions, Docker, Kubernetes, OpenShift

6 年

Well, Not all the Anonymous inner classes can be converted to lambda. Only those interfaces that contain single method to override.

要查看或添加评论,请登录

?? Saral Saxena ???????的更多文章

社区洞察

其他会员也浏览了