Java UnitIII Ppt
Java UnitIII Ppt
Functional Interfaces,
Lambda Expression,
Method References,
Stream API,
Default Methods,
Static Method,
ForEach Method,
Try-with-resources,
Local Variable Type Inference, Switch Expressions, Yield Keyword, Text Blocks,
Records, Sealed Classes
Lambda Expression
Lambda expression is a new and important feature of Java
which was included in Java SE 8.
It provides a clear and concise way to represent one method
interface using an expression.
The Lambda expression is used to provide the implementation
of an interface which has functional interface.
It saves a lot of code.
Why use Lambda Expression
Lambda Expression :
() -> { System.out.print(“Hello”); }
() -> System.out.print(“Hello”);
Lambda Expression Example:
One Parameter Syntax
public int m1(String s)
{
return s.length ();
}
Lambda Expression :
(String s) -> { return s.length(); }
(String s) -> return s.length();
s -> s.length();
Lambda Expression Example:
Two Parameter Syntax
public void sum (int a, int b)
{
System.out.print (a+b);
}
Lambda Expression :
(int a, int b) -> { System.out.print(a+b); }
(int a, int b) -> System.out.print(a+b);
(a,b) -> System.out.print(a+b);
Functional Interfaces
Lambda expression provides implementation of functional
interface.
3. }
6. int width=10;
10. };
11. d.draw();
12. }
13. }
With Lambda Expression and
Functional Interface
1. @FunctionalInterface //It is optional
2. interface Drawable{
4. }
5.
8. int width=10;
9.
13. };
14. d2.draw();
15. }
16. }
Java Method References
interface Sayable{
void say();
sayable.say();
Sayable sayable2 = new MethodRef1()::saySomething; // You can use anonymous object also
sayable2.say();
Reference to a Constructor
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
ClassName::new
Stream API
New Style
var name = "Welcome to tutorialspoint.com";
Switch Expressions
Yield Keyword
this.name = name;
this.age = age;
}
return name;
}
return age;
}
}
With Records
LinkedHashSet
HashSet
uses TreeSet uses TreeMap
Internal internally uses
LinkedHashMap internally to store
Working HashMap for
internally to store objects
storing objects
objects
If you don’t
If you want to
want to
maintain the If you want to sort the
maintain
When To insertion order of elements according to
insertion order
Use elements then you some Comparator then
but want to
can use use TreeSet
store unique
LinkedHashSet
objects
LinkedHashSet
HashSet gives While TreeSet gives
gives insertion,
O(1) complexity the performance of
Complexity removing, and
for insertion, order O(log(n)) for
of retrieving
removing, and insertion, removing,
Operations operations
retrieving and retrieving
performance in
objects operations.
order O(1).