INTRODUCTION
Java 8 came up with a lot of enhancements. Features like Lambda Expression and Streams plays a major role on simplicity and maintainable code.
This post aims to provide the outline of Java 8 new features.
- Lambda Expressions
- Functional Interfaces
- Method References
- Streams
- Interface Enhancements
- Collection Enhancements
- Date & Time API Enhancements
LAMBDA EXPRESSIONS
- Lambda expression enables functional programming in java which is not present till Java 8
- Simplifies the code and removes unwanted codes(boilerplate codes).
- @FunctionalInterface annotation helps to create our own Functional Interfaces. A functional interface can contain only one method. An example is a Runnable Interface.
- Syntax : argument(s) -> expression
- Lambda expression can be defined without argument, one argument or multiple arguments
- without argument
MyLambda myLambda = () -> System.out.println("Test");
myLambda.foo();
|
- one argument
(a) -> System.out.println(a);
|
- multiple argument
MyMath add = (a, b) -> a + b;
System.out.println("Sum is: " + add.calc(8, 4));
|
FUNCTIONAL INTERFACES
- Functional Interfaces are the java interfaces which will contain only one method.
- In Java 8, new package java.util.function has been introduced.
- Main interfaces are:
- Function - assignment for any lambda expressions
- Predicate
- Consumer
- Supplier
METHOD REFERENCES
- Method reference help to access the public & non-static method of any class.
- Syntax : Class::method
- Example: mylist.forEach(System.out::println)
STREAMS
- Streams are functional style.
- Mainly process the list of elements of any type.
- In Java 8, new package java.util.stream has been introduced.
- Main classes & Interfaces are
- Stream
- Collector
- Collectors
- Streams are processed without or multiple intermediate operations (intermediate streams) and terminal operations (final output).
- Intermediate operations are lazy operations which mean it will accept the input and wait for processing till the terminal operation is encountered. Example operations are
- filter
- map
- mapToInt
- Terminal operations are
- sum
- average
- min
- max
INTERFACE ENHANCEMENTS
- Java 8 provides another interesting feature in the interface like having concrete methods in it.
- concrete methods in the interfaces are either static or default access modifier.
Example:
public interface Test {
void food();
default void speak() {
System.out.println("i can't speak :(");
}
default double average() {
return 20 / 5;
}
static void fly() {
System.out.println("i can't fly :(");
}
static int add() {
return 5 + 4;
}
static List<String> cities() {
return Arrays.asList("Chennai", "Mumbai", "Bangalore");
}
}
|
Hope this post gives a brief introduction to Java 8 new features and enhancements.
Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!
No comments :
Post a Comment