Java 8 Features
Java 8 Features
Example 1:
Example 2:
Example 3:
B interface is declared as functional interface and two methods indirectly. So invalid for B.
Parent Reference can hold child object is valid.
Lambda expressions not replacement for .class files. They does not generate .class file.
Anonymous Inner Class vs Lambda Expressions || Session - 4
Default method() & Static method() inside Interface
Why default method is called defender or what is the reason to introduce default method?
When a new method is added then all the impl class will be effected. So it is optional and dummy
impl is in interface.
Default not allowed in classes. If same syntax while impl class then CE says “default not allowed in
classes only in interfaces”.
Object class methods are not allowed in interface. Since already available in Object class. All the
classes are sub classes of Object class.
Diamond Problem and Solution: Two interfaces with default implementation then implementation
class should override that method.
Call interface method from implemented class
If only static method better for interface instead of class. Since static method not required object
Interface static method should call using interface name only. Since interface static methods are not
available to the implementation classes.
Main method is allowed in interface from 1.8 Version because static methods are allowed.
If every method is static in a class then why to go for class is heavy weight.
For general utility methods go for interface instead of class.
Predefined Functional Interface: Predicate
Functional Interface:
Consumer:
Consumer Chaining:
BiPredicate:
BiConsumer:
Note: BiSupplier is not there
Problem for primitive Functional interface: As per the below example there is N times auto boxing
auto unboxing need to happen in for loop.
It will impact the performance.
3 types of interfaces based on primitive types int/double/long and method name standards are
based on return types. (AsInt Int is return type for that FI).
If input and return types are same then don’t use function go for UnaryOperator.
Where ever run method is required use already implemented m1 method.
Advantage of Method Reference: Code Reusability.
Syntax for Static and non-static reference:
Rule:
The arguments should match in method reference
Access specifiers not considered
These are the advantages of Constructor Reference(Code to create object and return that object).
Filter:
Map method:
Failed students count:
Whenever we are talking about min and max, it needs to be sorted either in ascending or descending
order.
Sub packages classes are not available to parent package. Inheritance not applicable in packages.
If you want to convert into collections use Arrays.
Date and Time New features:
To get current date and current system time.
Output:
Group By in Streams:
Local variables are minor collections are comes under young generation.