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

Features of Java 1.8

The document discusses new features introduced in Java 8 including functional interfaces, lambda expressions, default methods, streams API, and other utilities like StringJoiner and Optional; it provides examples of how to use functional interfaces, lambda expressions, default methods, and demonstrates intermediate and terminal stream operations like map, filter, sorted, collect, forEach, and reduce.

Uploaded by

Uttam Lanjewar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Features of Java 1.8

The document discusses new features introduced in Java 8 including functional interfaces, lambda expressions, default methods, streams API, and other utilities like StringJoiner and Optional; it provides examples of how to use functional interfaces, lambda expressions, default methods, and demonstrates intermediate and terminal stream operations like map, filter, sorted, collect, forEach, and reduce.

Uploaded by

Uttam Lanjewar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

There is list of below features of java 1.

8 as

Functional Interface

An Interface that contains exactly one abstract method is known as functional


interface.

It can have any number of default, static methods but can contain only one
abstract method.

Example-

package com.test;

@FunctionalInterface
public interface Test {

void getStudentName(String name);

package com.test;

public class Main implements Test {

@Override
public void getStudentName(String name) {
System.out.println(name);
}

public static void main(String[] args) {

Main main = new Main();


main.getStudentName("ashok");
}

Lambda Expression-

Why?

Less coding

Syntax- (argument-list) -> {body}

 Argument-list: It can be empty or non-empty as well.


 Arrow-token: It is used to link arguments-list and body of expression.
 Body: It contains expressions and statements for lambda expression.
No Parameter Syntax

() -> {
//Body of no parameter lambda
}

One Parameter Syntax

(p1) -> {
//Body of single parameter lambda
}

Two Parameter Syntax

(p1,p2) -> {
//Body of multiple parameter lambda
}
Example-

package com.test;

public interface Addition {

int add(int a,int b);

package com.test;

public class Main {

public static void main(String[] args) {

// Multiple parameters in lambda expression


Addition addition = (a, b) -> (a + b);
System.out.println(addition.add(10, 20));

// Multiple parameters with data type in lambda expression


Addition addition2 = (int a, int b) -> (a + b);
System.out.println(addition2.add(100, 200));
}
}
Output
30
300
Default method

Java provides a facility to create default methods inside the interface. Methods
which are defined inside the interface and tagged with default are known as
default methods. These methods are non-abstract methods.

Example-

package com.test;

public interface Example {

default void m1() {


System.out.println("this is default m1 method");
}
}

package com.test;

public class TestMain implements Example {

public static void main(String[] args) {

TestMain testMain=new TestMain();


testMain.m1();
}
}

Output
this is default m1 method

forEach () method-

The Java forEach() method is a utility function to iterate over a collection such
as (list, set or map) and stream. It is used to perform a given action on each the
element of the collection.

package com.test;

import java.util.HashMap;
import java.util.Map;

public class MapDemo {

public static void main(String[] args) {


Map<String, String> map = new HashMap<String, String>();

map.put("10", "ram");
map.put("11", "shyam");
map.put("12", "ganesh");

map.forEach((k, v) -> System.out.println("Key = " + k + ", Value


= " + v));
}
}

Output
Key = 11, Value = shyam
Key = 12, Value = ganesh
Key = 10, Value = ram

Optional class-

Java introduced a new class Optional in jdk8. It is a public final class and used to
deal with NullPointerException in Java application.

You must import java.util package to use this class. It provides methods which
are used to check the presence of value for particular variable.

Why?
package com.test;

public class MapDemo {

public static void main(String[] args) {

String[] str = new String[10];


String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);

}
}

Exception in thread "main" java.lang.NullPointerException


at com.test.MapDemo.main(MapDemo.java:8)

Here we are getting exception, to avoid this type of exception, we should go for
optional class

package com.test;

import java.util.Optional;

public class MapDemo {

public static void main(String[] args) {


String[] str = new String[10];
Optional<String> checkNull = Optional.ofNullable(str[5]);
if (checkNull.isPresent()) { // check for value is present or not
String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
} else
System.out.println("string value is not present");

}
}

Output
string value is not present.

Java String Joiner-


Java added a new final class StringJoiner in java.util package. It is used to
construct a sequence of characters separated by a delimiter. Now, you can
create string by passing delimiters like comma(,), hyphen(-) etc

Example
import java.util.StringJoiner;

public class Example {

public static void main(String[] args) {


StringJoiner stringJoiner = new
StringJoiner(","); // passing comma(,) as delimiter

// Adding values to StringJoiner


stringJoiner.add("Ram");
stringJoiner.add("Shyam");
stringJoiner.add("ashok");
stringJoiner.add("ajay");
System.out.println(stringJoiner);
}
}

Output
Ram,Shyam,ashok,ajay

Stream API
The Stream API is used to process collections of objects. A stream is a
sequence of objects that supports various methods which can be pipelined to
produce the desired result.
Different Operations On Streams-
Intermediate Operations:
1. map: The map method is used to returns a stream consisting of the
results of applying the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x-
>x*x).collect(Collectors.toList());

2. filter: The filter method is used to select elements as per the


Predicate passed as argument.
List names =
Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s-
>s.startsWith("S")).collect(Collectors.toList());

3. sorted: The sorted method is used to sort the stream.


List names =
Arrays.asList("Reflection","Collection","Stream");
List result =
names.stream().sorted().collect(Collectors.toList());

Terminal Operations:
1. collect: The collect method is used to return the result of the
intermediate operations performed on the stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x-
>x*x).collect(Collectors.toSet());

2. forEach: The forEach method is used to iterate through every


element of the stream.
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x).forEach(y-
>System.out.println(y));

3. reduce: The reduce method is used to reduce the elements of a


stream to a single value.
The reduce method takes a BinaryOperator as a parameter.
List number = Arrays.asList(2,3,4,5);
int even = number.stream().filter(x-
>x%2==0).reduce(0,(ans,i)-> ans+i);
Here ans variable is assigned 0 as the initial value and i is added to
it .
//a simple program to demonstrate the use of stream in java
import java.util.*;
import java.util.stream.*;

class Demo
{
public static void main(String args[])
{

// create a list of integers


List<Integer> number = Arrays.asList(2,3,4,5);

// demonstration of map method


List<Integer> square = number.stream().map(x -> x*x).
collect(Collectors.toList());
System.out.println(square);

// create a list of String


List<String> names =
Arrays.asList("Reflection","Collection","Stream");

// demonstration of filter method


List<String> result = names.stream().filter(s->s.startsWith("S")).
collect(Collectors.toList());
System.out.println(result);

// demonstration of sorted method


List<String> show =
names.stream().sorted().collect(Collectors.toList());
System.out.println(show);

// create a list of integers


List<Integer> numbers = Arrays.asList(2,3,4,5,2);

// collect method returns a set


Set<Integer> squareSet =
numbers.stream().map(x->x*x).collect(Collectors.toSet());
System.out.println(squareSet);

// demonstration of forEach method


number.stream().map(x->x*x).forEach(y->System.out.println(y));

// demonstration of reduce method


int even =
number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);

System.out.println(even);
}}
Output

[4, 9, 16, 25]


[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6

You might also like