0% found this document useful (0 votes)
88 views

16.java8 Features

1. Java 8 introduced lambda expressions to provide concise and anonymous functions. Lambda expressions can have zero to multiple parameters and can omit curly braces for single statement bodies. 2. Functional interfaces with a single abstract method were designated as @FunctionalInterface and can be implemented using lambda expressions. 3. Default methods were added to interfaces to enable adding new functionality while maintaining binary compatibility. Default methods are declared in interfaces with the default keyword.

Uploaded by

Vignesh Vicky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

16.java8 Features

1. Java 8 introduced lambda expressions to provide concise and anonymous functions. Lambda expressions can have zero to multiple parameters and can omit curly braces for single statement bodies. 2. Functional interfaces with a single abstract method were designated as @FunctionalInterface and can be implemented using lambda expressions. 3. Default methods were added to interfaces to enable adding new functionality while maintaining binary compatibility. Default methods are declared in interfaces with the default keyword.

Uploaded by

Vignesh Vicky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

JAVA 8 - Features:

1. Lambda Expression:
• In Java programming language, a Lambda expression (or function)
is just an anonymous function
• A function with no name and without being bound to an identifier.
• They are written exactly in the place where it’s needed, typically
as a parameter to some other function.
• A lambda expression can have zero, one or more parameters.
• The type of the parameters can be explicitly declared or it can be
inferred from the context.
• Multiple parameters are enclosed in mandatory parentheses and
separated by commas. Empty parentheses are used to represent
an empty set of parameters.
() -> expression
(param1, param2, param3) -> expression
• When there is a single parameter, if its type is inferred, it is not
mandatory to use parentheses. e.g. a -> return a*a.
• If the body of the lambda expression has a single statement, curly
brackets are not mandatory and the return type of the
anonymous function is the same as that of the body expression.
When there is more than one statement in the body then these
must be enclosed in curly brackets.
(parameters) -> { statements; }
Example:
(x, y) -> x + y
Example 1: Using lambda expression to iterate over a List and perform
some action on list elements
In the given example, we are iterating over the list and printing all the
list elements in the standard output. We can perform any desired
operation in place of printing them.
List<String> pointList = new ArrayList();
pointList.add("1");
pointList.add("2");
pointList.forEach(p -> { System.out.println(p); } );
Example 2: Using lambda expression to create and start a Thread in Java
In given example, we are passing the instance of Runnable interface
into the Thread constructor.
new Thread(
() -> System.out.println("My Runnable");
).start();
2. Functional Interface:
• Single Abstract Method interfaces (SAM Interfaces) is not a new
concept. It means interfaces with only one single method.
• From Java 8, SAM Interfaces will also be referred to as functional
interfaces.
• Java 8 enforces the rule of single responsibility by marking these
interfaces with a new annotation i.e. @FunctionalInterface.
For example, new definition of Runnable interface is like this:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("howtodoinjava");
}
}).start();
If we use the lambda expression for this task then code will be :
new Thread(
() -> {
System.out.println("My Runnable");
}
).start();
3. Default Methods:
• Java 8 allows you to add non-abstract methods in interfaces.
These methods must be declared default methods.
• Default methods were introduces in java 8 to enable the
functionality of lambda expression.
• Default methods enable you to add new functionality to the
interfaces of your libraries and ensure binary compatibility with
code written for older versions of those interfaces.
Example:
public interface Moveable {
default void move(){
System.out.println("I am moving");
}
}
public class Animal implements Moveable{
public static void main(String[] args){
Animal tiger = new Animal();
tiger.move();
}
}
Output:
I am moving
4. Streams:
• Another major change introduced Java 8 Streams API, which
provides a mechanism for processing a set of data in various ways
that can include filtering, transformation, or any other way that
may be useful to an application.
• Streams API in Java 8 supports a different type of iteration where
you simply define the set of items to be processed, the
operation(s) to be performed on each item, and where the output
of those operations is to be stored.
Different Operations On Streams:
Example:
List<String> memberNames = new ArrayList<>();
memberNames.add("Amitabh");
memberNames.add("Shekhar");
memberNames.add("Aman");
memberNames.add("Rahul");
memberNames.add("Shahrukh");
memberNames.add("Salman");
memberNames.add("Yana");
memberNames.add("Lokesh");
These core methods have been divided into 2 parts given below:

1. Intermediate Operations:
• Intermediate operations return the stream itself so you can chain
multiple methods calls in a row. Let’s learn important ones.
1.1. Stream.filter()
• The filter() method accepts a Predicate to filter all elements of the
stream.
• This operation is intermediate which enables us to call another
stream operation (e.g. forEach()) on the result.
memberNames.stream().filter((s) -> s.startsWith("A"))
.forEach(System.out::println);
Program Output:
Amitabh
Aman
1.2. Stream.map()
• The map() intermediate operation converts each element in the
stream into another object via the given function.
• The following example converts each string into an UPPERCASE
string.
• But we can use map() to transform an object into another type as
well.
memberNames.stream().filter((s) -> s.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);
Program Output:
AMITABH
AMAN
1.3. Stream.sorted()
• The sorted() method is an intermediate operation that returns a
sorted view of the stream.
• The elements in the stream are sorted in natural order unless we
pass a custom Comparator.
• Please note that the sorted() method only creates a sorted view of
the stream without manipulating the ordering of the source
Collection.

memberNames.stream().sorted()
.map(String::toUpperCase)
.forEach(System.out::println);
Program Output:
AMAN
AMITABH
LOKESH
RAHUL
SALMAN
SHAHRUKH
SHEKHAR
YANA
1.4. Stream.distinct()
Removes the duplicate value in the list.
nameList.stream().sorted().distinct().forEach(Sy
stem.out::println);

2. Terminal operations:
• Terminal operations return a result of a certain type after
processing all the stream elements.
• Once the terminal operation is invoked on a Stream, the iteration
of the Stream and any of the chained streams will get started.
• Once the iteration is done, the result of the terminal operation is
returned.
2.1. Stream.forEach()
• The forEach() method helps in iterating over all elements of a
stream and perform some operation on each of them.
• The operation to be performed is passed as the lambda
expression.
memberNames.forEach(System.out::println);
2.2. Stream.collect()
• The collect() method is used to receive elements from a steam
and store them in a collection.
List<String> memNamesInUppercase =
memberNames.stream().sorted()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.print(memNamesInUppercase);
Program Output:
[AMAN, AMITABH, LOKESH, RAHUL, SALMAN, SHAHRUKH, SHEKHAR,
YANA]
2.3. Stream.match()
• Various matching operations can be used to check whether a
given predicate matches the stream elements.
• All of these matching operations are terminal and return a
boolean result.
boolean matchedResult = memberNames.stream()
.anyMatch((s) -> s.startsWith("A"));
System.out.println(matchedResult);
matchedResult = memberNames.stream()
.allMatch((s) -> s.startsWith("A"));
System.out.println(matchedResult);
matchedResult = memberNames.stream()
.noneMatch((s) -> s.startsWith("A"));
System.out.println(matchedResult);
Program Output:
true
false
false
2.4. Stream.count()
• The count() is a terminal operation returning the number of
elements in the stream as a long value.
long totalMatched = memberNames.stream()
.filter((s) -> s.startsWith("A"))
.count();
System.out.println(totalMatched);
Program Output:
2
2.5. Stream.reduce()
• The reduce() method performs a reduction on the elements of the
stream with the given function.
• The result is an Optional holding the reduced value.
• In the given example, we are reducing all the strings by
concatenating them using a separator #.
Optional<String> reduced = memberNames.stream()
.reduce((s1,s2) -> s1 + "#" + s2);
reduced.ifPresent(System.out::println);
Program Output:
Amitabh#Shekhar#Aman#Rahul#Shahrukh#Salman#Yana#Lokesh

2.6. Stream.findFirst()
• The findFirst() method will return the first element from the
stream and then it will not process any more elements.
String firstMatchedName = memberNames.stream()
.filter((s) -> s.startsWith("L"))
.findFirst()
.get();
System.out.println(firstMatchedName);
Program Output:
Lokesh

You might also like