JAVA 8 Features
Functional Interfaces
• An interface that contains only one abstract method.
• A functional interface can have any number of default and static
methods.
• @FunctionalInterface annotation is optional.
• Lambda Expression is use to provide implementation to functional
interface.
• Examples: Runnable, ActionListener , Comparable.
Lambda Expression
• Lambda expressions basically express instances of functional
interface.
• It is an anonymous function that doesn’t have any name and doesn’t
belong to any class.
• It provide a concise way to represent abstract method via expression.
Syntax
parameter -> expression
(parameter1, parameter2) -> expression
(parameter1, parameter2) -> { code block }
Stream
• All the classes and interfaces in the Stream API is in java.util.stream
package.
• Stream consumes a source, performs operations on it and returns a
result.
• Streams can be created from Collections i.e lists,sets,Arrays,lines of a
file.
• Mainly two operations are performed using streams are Intermediate
and Terminal operations.
Intermediate And Terminal operations
• Intemediate operations:-filter,map or sort return a stream so we can
chain multiple operations.
• Terminal operations:-forEach,collect or reduce either void or return
non–stream result
-Terminal operations return a result of a certain type after processing
all the stream elements.
How to work with Stream in Java
1. Create a stream. Eg-Stream.of (object),collection_type.stream()
2. Perform intermediate operations on the initial stream to transform
it into another stream.eg filter(),map().
3. Perform terminal operation on the final stream to get the result.
eg.count()
Selection Operations
• filter()
reads the data from a stream and returns a new stream after transforming the data based on the
given condition.
Method Signature : Stream<T> filter(Predicate<T> predicate)
• distinct()
Selects only unique elements
Method Signature : Stream<T> distinct()
• skip()
Skips first n elements
Method Signature : Stream<T> skip(long n)
limit()
Selects first n elements
Method Signature : Stream<T> limit(long maxSize)
Mapping Operations
• map()
Is used to transform one object to other by applying a function.
Method Signature : Stream<R> map(Function<T, R> mapper);
Example: memberNames.stream().filter((s) -> s.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);
Terminal operations
• forEach()
-helps in iterating over all elements of a stream and perform some
operation on each of them.
• collect()
- used to receive elements from a steam and store them in a collection
• count()
-used to returning number of elements in a stream as long value.