Professional Documents
Culture Documents
Lambda Expression Vs Anonymous Inner Class - Making Java Easy To Learn
Lambda Expression Vs Anonymous Inner Class - Making Java Easy To Learn
example. Suppose we have to perform sorting on some set of Strings. For that we will take
an array to given Strings, then we will implement the Comparator interface to sort them.
First, we will implement it using anonymous inner class, then by using Lambda Expression
in order to have clear picture on both.
return s1.compareTo(s2);
});
Arrays.stream(mobiles).forEach(System.out::println);
Stream.of(mobiles).forEach(System.out::println);
Output :
Apple
Blackberry
Lenovo
Oppo
Samsung
Sony
Xiaomi
https://javatechonline.com/lambda-expression-vs-anonymous-inner-class/ 2/7
9/22/22, 2:30 PM Lambda Expression Vs Anonymous Inner Class | Making Java Easy To Learn
Apple
Blackberry
Lenovo
Oppo
Samsung
Sony
Xiaomi
For example, from the above code snippet below code is the implementation of
Comparator interface by using Anonymous Inner class.
new Comparator<String>() { public int compare(String s1, String s2) { return s1.compareTo(s2);
“this” keyword inside Lambda Expression “this” keyword inside anonymous inner
always refers to current outer class object ie. class always refers to current anonymous
enclosing class object. Inner class object but not outer class
object.
Lambda expression can’t extend any class In contrast, an Anonymous inner class can
like abstract and concrete classes. extend any class like abstract and
concrete classes.
https://javatechonline.com/lambda-expression-vs-anonymous-inner-class/ 3/7
9/22/22, 2:30 PM Lambda Expression Vs Anonymous Inner Class | Making Java Easy To Learn
For Lambda Expression at the time of For Anonymous Inner class at the time of
compilation, no .class file fill be generated. compilation, a separate .class file will be
generated.
Tagged anonymous inner class anonymous inner class can anonymous inner class in java anonymous
inner class vs lambda Difference between Lambda Expression & Anonymous Inner class java lambda vs
anonymous class Lambda Expression & Anonymous Inner class lambda expression avoid unwanted anonymous
inner class Lambda Expression vs Anonymous Inner class Use of Lambda Expression vs Anonymous Inner class
what is anonymous class in java
Previous article
https://javatechonline.com/lambda-expression-vs-anonymous-inner-class/ 4/7