[Go to site: main page, start]

0% found this document useful (0 votes)
6 views35 pages

Java 8 Example

The document outlines key features of Java 1.8, including changes to interfaces such as default and static methods, the introduction of functional interfaces, and the use of lambda expressions for functional programming. It explains various functional interfaces like Predicate, Consumer, Supplier, and Function, along with examples of their usage. Additionally, it covers method references, the Stream API, and enhancements in the Date & Time API, as well as I/O stream changes.

Uploaded by

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

Java 8 Example

The document outlines key features of Java 1.8, including changes to interfaces such as default and static methods, the introduction of functional interfaces, and the use of lambda expressions for functional programming. It explains various functional interfaces like Predicate, Consumer, Supplier, and Function, along with examples of their usage. Additionally, it covers method references, the Stream API, and enhancements in the Date & Time API, as well as I/O stream changes.

Uploaded by

SAURABH SUPE
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

================= => Here i am taking one interface with one abstract

method. All the classes which are implementing that


Java 1.8 Features
interface should overide interface method(s).
=================
interface Vehicle {
1) Interface changes
public abstract void startVechicle ( );
1.1 ) Default Methods
}
1.2 ) Static Methods
class Car implements Vehicle {
2) Functional Interfaces (@FunctionalInterface)
public void startVehicle ( ) {
2.1 ) Predicate & BiPredicate
// logic to start car
2.2 ) Consumer & BiConsumer
}
2.3 ) Supplier
}
2.4 ) Function & BiFunction
class Bus implements Vehicle {
3) Lambda Expressions
public void startVehicle ( ) {
4) Method References & Constructor References
// logic to start bus
5) ****** Stream API ********
}
6) Optional class (to avoid null pointer exceptions)
}
7) Spliterator
class Bike implements Vehicle {
8) StringJoiner
public void startVehicle ( ) {
9) forEach ( ) method
// logic to start bike
10) Date & Time API
}
11) Nashron Engine
}
12) I/O Stream Changes ([Link](Path p))
=> If we add new method in interface then Car, Bike
13) Base64 Encoding & Decoding and Bus will fail at compile time.

=> To overcome above problem we will use Default &


Static methods
================
1) Interface can have concreate methods from 1.8v
Interface changes
2) Interface concrete method should be default or
================ static
-> Interface means collection of abstract methods 3) interface default methods we can override in impl
Note: The method which doesn't contain body is classes
called as abstract method 4) interface static methods we can't overide in impl
-> A class can implement interface using "implements" classes

-> When a class is implementing interface its 5) We can write multiple default & static methods in
mandatory that class should implement all abstract interface
methods of that interface othewise class can't be 6) Default & Static method introduced to provide
compile. backward compatability

Ex: forEach ( ) method added in [Link]


interface as default method in 1.8v
=========== -> Lambda Expressions introduced in Java to enable
Functional Programming.
package [Link];
==============
interface Vehicle {
What is Lambda
public void start();
=============
public default void m1() {
-> Lambda is an anonymous function
}
- No Name
public default void m2() {
- No Modifier
}
- No Return Type
public static void clean() {
[Link]("cleaning completed..."); Ex:-1

} public void m1 ( ) { s.o.p("hi");

} }

public class Car implements Vehicle { ( ) -> { s.o.p ("hi") }

public void start() { Note: When we have single line in body then curly
[Link]("car starte..."); braces are optional

} ( ) -> s.o.p ("hi");

public static void main(String[] args) { Ex:-2


Car c = new Car();
public void add (int a, int b){
[Link](); [Link]();
s.o.p(a+b);
}}
}
============================================
( int a, int b) -> { s.o.p (a+b) } ;
=====================
(or)
Lambda Expressions
(int a, int b) -> s.o.p (a+b);
====================
(or)
-> Introdced in java 1.8v
Lambda Expression : (a, b) -> s.o.p(a+b);
-> Java is called as Object Oriented Programming
language. Everything will be represented using Classes
and Objects.

-> From 1.8v onwards Java is also called as Functional


Programming Language. Ex:-3

-> In OOP language Classes & Objects are main public int getLength (String name) {
entities. We need to write methods inside the class return [Link] ( );
only.
}
-> Functional Programming means everything will be
represented in the form functions. Functions can exist (String name) -> { return [Link] ( ) };
outside of the class. Functions can be stored into a (String name) -> return [Link] ( ) ;
reference variable. A function can be passed as a
parameter to other methods. (name) -> return [Link] ( );

Lambda Expression : name -> [Link] ( ) ;


Ex:-4 -> The above interfaces are provided in
[Link] package
public Double getEmpSalary (Employee emp) {
========
return [Link] ( );
Predicate
}
========
Lambda Expression : emp -> [Link] ( );
-> It is predefined Functional interface
==================
-> It is used check condition and returns true or false
Functional Interfaces
value
==================
-> Predicate interface having only one abstract
-> The interface which contains only one abstract method that is test (T t)
method is called as Functional Interface
interface Predicate{
-> Functional Interfaces are used to invoke Lambda
boolean test(T t);
expressions
}
-> Below are some predefined functional interfaces

Runnable ------------> run ( )


method

// Predicate Example

Callable ----------> call ( )


method
package [Link].java8;

Comparable ------->
import [Link];
compareTo ( )

-> To represent one interface as Functional Interface


we will use @FunctionalInterface annotation. public class PredicateDemo {

@FunctionalInterface public static void main(String[] args) {


public interface MyInterface {

public void m1( ); Predicate<Integer> p = i -> i > 10;


} [Link]([Link](5));
Note: When we write @FunctionalInterface then our [Link]([Link](15));
compiler will check interface contains only one
abstract method or not. }

-> In Java 8 several predefined Functional interfaces


got introduced they are }
1) Predicate & BiPredicate

2) Consumer & BiConsumer ============================================


3) Supplier ===========================================

4) Function & BiFunction Task: Declare names in an array and print names
which are starting with 'A' using lambda expression.
String[ ] names = {"Anushka", package [Link].java8;
"Anupama", "Deepika", "Kajol", "Sunny" };

import [Link];
============================================
import [Link];
============================================
= import [Link];

package [Link].java8; class Person {

import [Link]; String name;

int age;
public class PredicateDemo2 {

Person(String name, int age) {


public static void main(String[] args) { [Link] = name;

[Link] = age;
String[ ] names = { "Anushka", }
"Anupama", "Deepika", "Kajol", "Sunny" };
}

Predicate<String> p = name ->


[Link](0) == 'A'; public class PredicatePersonsDemo {

for (String name : names) { public static void main(String[] args) {

if ( [Link](name) ) {
Person p1 = new Person("John", 26);
[Link](name); Person p2 = new Person("Smith", 16);
} Person p3 = new Person("Raja", 36);
} Person p4 = new Person("Rani", 6);
}

} List<Person> persons =
[Link](p1, p2, p3, p4);

============================================
================================ Predicate<Person> predicate = p ->
Task-2 : Take list of persons and print persons whose [Link] >= 18;
age is >= 18 using Lambda Expression

============================================ for (Person person : persons) {


================================
if ([Link](person)) {
[Link] = location;
[Link]([Link]);
[Link] = dept;
}
}
}
}
}

}
public class PredicateJoinDemo {

================
public static void main(String[] args) {
Predicate Joining
Employee e1 = new Employee("Anil",
=============== "Chennai", "DevOps");

Employee e2 = new Employee("Rani",


"Pune", "Networking");
-> To combine multiple predicates we will use
Predicate Joining Employee e3 = new
Employee("Ashok", "Hyd", "DB");

Employee e4 = new
and ( ) method
Employee("Ganesh", "Hyd", "DB");

or ( ) method
List<Employee> emps =
[Link](e1, e2, e3, e4);

Task-1 : Print emp names who are working in Hyd


location in DB team.
Predicate<Employee> p1 = (e) ->
[Link]("Hyd");

package [Link].java8; Predicate<Employee> p2 = (e) ->


[Link]("DB");

Predicate<Employee> p3 = (e) ->


import [Link]; [Link]("A");
import [Link];

import [Link]; // Predicate Joining

Predicate<Employee> p =
class Employee { [Link](p2).and(p3);

String name; for (Employee e : emps) {

String location; if ([Link](e)) {

String dept;
[Link]([Link]);

}
Employee(String name, String location, String
dept) { }

[Link] = name; }
} return otp;

};

==========================

Supplier Functional Interface [Link]([Link]());

========================== [Link]([Link]());

[Link]([Link]());

-> Supplier is a predefined functional interface [Link]([Link]());


introduced in java 1.8v
[Link]([Link]());

[Link]([Link]());
-> It contains only one abstract method that is get ( )
}
method
}

-> Supplier interface will not take any input, it will only
returns the value. ==========================

Consumer Functional Interface


Ex: ==========================
----

-> Consumer is predefined functional interface


OTP Generation

-> It contains one abstract method i.e accept (T t)

-> Consumer will accept input but it won't return


anything
package [Link].java8;

Note: in java 8 forEach ( ) method got introduced.


import [Link];
forEach(Consumer consumer) method will take
Consumer as parameter.

public class SupplierDemo {

public static void main(String[] args) { package [Link].java8;

Supplier<String> s = () -> { import [Link];

String otp = ""; import [Link];

for (int i = 1; i <= 6; i++) { import [Link];

otp = otp + (int)


([Link]() * 10);
public class ConsumerDemo {
}
Consumer ----> will take input ----> will not return
anything ===> accept ( )
public static void main(String[] args) {

Function -----> will take input ---> will return output


Consumer<String> c = (name) ->
===> apply ( )
[Link](name + ", Good Evening");

[Link]("Ashok");
=========================
[Link]("John");
Function Functional Interface
[Link]("Rani");
=========================

List<Integer> numbers =
[Link](10, 20, 30, 40); -> Function is predefined functional interface

// for loop

// for each loop -> Funcation interface having one abstract method i.e
apply(T r)
// iterator

// list iterator
interface Function<R,T>{

R apply (T t);
[Link](i ->
[Link](i)); }

} -> It takes input and it returns output

============================================
=============
package [Link].java8;
Retrieve student record based on student id and
return that record
import [Link];
============================================
=============

public class FunctionDemo {

Predicate ------> takes inputs ----> returns true or false public static void main(String[] args) {
===> test ( )

Function<String, Integer> f = (name) -


Supplier -----> will not take any input---> returns > [Link]();
output ===> get ( )

[Link]([Link]("ashokit"));
[Link]([Link]("hyd")); public static void m2() {

[Link]([Link]("sachin")); [Link]("This is m2( )


method");

}
}

}
public static void main(String[] args) {

MyInterface mi = MethodRef::m2;
============================================
============= mi.m1();

Task : Take 2 inputs and perform sum of two inputs }


and return ouput
}
============================================
=============

package [Link].java8;

BiFunction<Integer,Integer,Integer> bif = (a,b) -> a+b;


public class InstanceMethodRef {

Integer sum = [Link](10,20);


public void m1() {

for (int i = 1; i <= 5; i++) {

[Link](i);
================
}
Method References
}
=================

public static void main(String[] args) {


-> Method reference means Reference to one method
from another method

InstanceMethodRef im = new
InstanceMethodRef();

package [Link].java8;
Runnable r = im::m1;

Thread t = new Thread(r);


@FunctionalInterface

interface MyInterface {
[Link]();
public void m1();
}
}
}

public class MethodRef {


@Override

public class Test { public void run() {

for (int i = 1; i <= 5; i++) {

public static void main(String[] args) { [Link](i);

// Doctor d = new Doctor(); }

Supplier<Doctor> s = Doctor::new; public static void main(String[] args) {

Doctor doctor = [Link](); ThreadDemo1 td = new


ThreadDemo1();

[Link]([Link]()); Thread t = new Thread(td);

[Link]();

} }

class Doctor { package [Link].java8;

public Doctor() { // Approach-2

[Link]("Doctor public class ThreadDemo2 {


constructor....");

}
public static void main(String[] args) {
}

Runnable r = new Runnable() {

@Override
============================================
public void run() {
===============================
for (int i = 1; i <= 5;
Task : WAJP to print numbers from 1 to 5 using Thread
i++) {
with the help of Runnable interface

============================================
[Link](i);
================================
}

};
//Approach-1

public class ThreadDemo1 implements Runnable {


Thread t = new Thread(r);
[Link](); import [Link];

} import [Link];

} import [Link];

// Approach - 3 using Lambda Expression public class NumbersSort1 {

package [Link].java8;

public static void main(String[] args) {

public class ThreadDemo3 {

ArrayList<Integer> al = new
ArrayList<>();
public static void main(String[] args) {
[Link](5);

[Link](3);
Runnable r = () -> {
[Link](4);
for (int i = 1; i <= 5; i++) {
[Link](1);
[Link](i);
[Link](2);
}

};
[Link]("Before Sort :: " +
al);
Thread t = new Thread(r);

[Link]();
[Link](al, new
} NumberComparator());

}
[Link]("After Sort :: " +
al);

}
============================================
======================

Task: WAJP to store numbers in ArrayList and sort }


numbers in desending order

============================================
class NumberComparator implements
======================
Comparator<Integer> {

@Override

public int compare(Integer i, Integer j) {


// Approach-1 ( without Lambda)
if (i > j) {

return -1;
package [Link].java8;
} else if (i < j) {

return 1;
} ==========================

return 0; forEach (Consumer c) method

} ===========================

-> forEach (Consumer c) method introduced in java


1.8v

// Approach-2 ( with Lambda)


-> forEach ( ) method added in Iterable interface

package [Link].java8;
-> forEach ( ) method is a default method (it is having
body)
import [Link];

import [Link];
-> This is method is used to access each element of
the collection (traverse collection from start to end)

public class NumbersSort1 {

public static void main(String[] args) { package [Link].java8;

ArrayList<Integer> al = new import [Link];


ArrayList<>();

[Link](5);
public class NumbersSort1 {
[Link](3);

[Link](4);
public static void main(String[] args) {
[Link](1);

[Link](2);
ArrayList<Integer> al = new
ArrayList<>();

[Link]("Before Sort :: " + [Link](5);


al);
[Link](3);

[Link](4);
[Link](al, (i, j) -> (i > j) ? -1 :
[Link](1);
1);
[Link](2);

[Link]("After Sort :: " +


al); [Link](i -> [Link](i));

} }

} }
==============

StringJoiner StringJoiner sj2 = new StringJoiner("-",


"(", ")");
==============
[Link]("ashok");

[Link]("it");
-> [Link] class introduced in java 1.8v
[Link]("java");

[Link](sj2); // (ashok-it-
-> It is used to join more than one String with
java)
specified delimiter

}
-> We can concat prefix and suffix while joininging
strings using StringJoiner

StringJoiner sj = new StringJoiner


(CharSequence delim);

StringJoiner sj = new StringJoiner


=============
(CharSequence delim, CharSequence prefix,
CharSequence suffix); Optional Class

=============

-> [Link] class introduced in java 1.8v

package [Link].java8; -> Optional class is used to avoid


NullPointerExceptions in the program

import [Link];

Q) What is NullPointerException (NPE) ?


public class StringJoinerDemo {

Ans) When we perform some operation on null value


public static void main(String[] args) {
then we will get NullPointerException

StringJoiner sj1 = new StringJoiner("-


");
String s = null;
[Link]("ashok");

[Link]("it");
[Link] ( ) ; // NPE
[Link]("java");

[Link](sj1); // ashok-it-
java
-> To avoid NullPointerExceptions we have to } else {
implement null check before performing operation on
return null;
the Object like below.
}

}
String s = null;

// with Optional Object


if( s! = null ) {
public Optional<String> getUsername(Integer
id) {
[Link]([Link] ( ));
String name = null;
}
if (id == 100) {

name = "Raju";

} else if (id == 101) {

name = "Rani";
Note: In project there is no gaurantee that every
programmer will implement null checks. If any body } else if (id == 102) {
forgot to implement null check then program will run
into NullPointerException. name = "John";

-> To avoid this problem we need to use Optional class return [Link](name);
like below. }

package [Link].java8;

package [Link].java8;
import [Link];

import [Link];
public class User { import [Link];

public class MsgService {


// Without Optional object

public String getUsernameById(Integer id) { public static void main(String[] args) {


if (id == 100) {

return "Raju"; Scanner s = new Scanner([Link]);


} else if (id == 101) {

return "Rani"; [Link]("Enter User ID");


} else if (id == 102) { int userId = [Link]();
return "John";
Note: When we are performing database operations
then we will use [Link] class.
User u = new User();

/*String userName =
[Link](userId); -> For normal Date related operations we will use
[Link] class
String msg = [Link]()
+ ", Hello";

[Link](msg);*/ Date d = new Date ( );

[Link](d);

Optional<String> username =
[Link](userId);
Note: When we create Object for Date class, it will
represent both date and time.

if([Link]()) {

String name = [Link](); -> If we want to get only date or only time then we
need to format it using SimpleDateFormat class.

[Link]([Link]()+",
Hello");

}else {
========================
[Link]("No Data
[Link]
Found");
=======================
}

}
-> SimpleDateFormat is a predefined class in [Link]
}
pacakage

-> This class provided methods to perform Date


conversions

=======================

Date & Time API Changes

======================= Date to String conversion ===>


String format (Date d)

-> In java we have below 2 classes to represent Date


String to Date conversion ===> Date
parse(String str)
1) [Link]

2) [Link]
// Date Conversions Example

package [Link].java8;
=> To overcome the problems of [Link] class
java 1.8 introduced Date API changes
import [Link];

import [Link];
=> In java 1.8 version, new classes got introduced to
deal with Date & Time functionalities
public class DateDemo {

1) [Link]
public static void main(String[] args) throws (it will deal with only date)
Exception {

2) [Link]
Date date = new Date(); (it will deal with only time)

[Link](date);
3)
[Link] (it will deal with both date &
// Converting Date to String time)
SimpleDateFormat sdf1 = new
SimpleDateFormat("dd/MM/yyyy");

String format1 = [Link](date);

[Link](format1);
// Java 1.8 Date API Example

SimpleDateFormat sdf2 = new


SimpleDateFormat("MM/dd/yyyy"); package [Link].java8;

String format2 = [Link](date);

[Link](format2); import [Link];

import [Link];

// Convert String to Date import [Link];

SimpleDateFormat sdf3 = new import [Link];


SimpleDateFormat("yyyy-MM-dd");
import [Link];
Date parsedDate = [Link]("2022-
12-20");
public class NewDateDemo {
[Link](parsedDate);

public static void main(String[] args) {


}

}
LocalDate of = [Link](2021, 1,
20);
============================================
[Link](of);
============================================
=

LocalDate date = [Link]();


[Link](date); Duration duration =
[Link]([Link]("18:00"),
[Link]());
date = [Link](3);
[Link](duration);
[Link](date);
}

}
date = [Link](1);

[Link](date);

date = [Link](2);
=================
[Link](date);

1) What are new changes in java 8 version


boolean leapYear =
[Link]("2020-12-22").isLeapYear();
2) Interface Changes
[Link]("Leap Year :: " +
leapYear);

2.1 ) Default Methods

boolean before = 2.2 ) Static Methods


[Link]("2021-12-
22").isBefore([Link]("2022-12-22"));
3) Why Default & Static method introduced in java 8
[Link]("Before Date : " +
before);

4) Lambda Expressions Introduction


LocalTime time = [Link]();

[Link](time); 5) How to write Lambda Expression


time = [Link](2);

[Link](time); 6) How to invoke lambda expression

LocalDateTime datetime = 7) Functional Interfaces


[Link]();

[Link](datetime);
7.1) Predicate & BiPredicate

7.2) Supplier
Period period =
[Link]([Link]("1991-05-20"), 7.3) Consumer & BiConsumer
[Link]()); 7.4) Function & BiFunction
[Link](period);

8) Collections Sorting using Lambda


9) Thread Creation Using Lambda -> Source of data for the Stream can be array or
collection

10) Method References & Constructor References


===============================

Few Important Points About Streams


11) [Link] class
===============================

12) [Link] class


1) Stream is not a data structure. Stream means bunch
of operations applied on source data. Source can be
13) forEach ( Consumer c ) method collection or array.

14) Date & Time API Changes 2) Stream will not change original data structure of
the source (It will just process the data given by the
source.)
14.1) LocalDate

14.2) LocalTime

14.3) LocalDateTime ===============


14.4) Period Stream Creation
14.5) Duration ===============

=========== -> In Java we can create Stream in 2 ways


Stream API

=========== 1) [Link] (e1, e2, e3,


e4.....)

-> Stream API introduced in java 1.8v


2) stream ( ) method

-> Stream API is used to process the data

Note: Collections are used to store the data


// Java Program to Create Stream

-> Stream API is one of the major features added in


java 1.8v package [Link];

-> Stream in java can be defined as sequence of import [Link];


elements that comes from a source.
import [Link];
public class FirstDemo {

-> Intermediate Operational methods will perform


operations on the stream and returns a new Stream
public static void main(String[] args) {

Ex: filter ( ) ,
// Approach-1
map ( ) etc....
Stream<Integer> stream1 =
[Link](1, 2, 3, 4, 5);

-> Terminal Operational methods will take input and


ArrayList<String> names = new
will provide result as output.
ArrayList<>();

[Link]("John");
Ex: count ( )
[Link]("Robert");

[Link]("Orlen");

===================
// Approach-2
Filtering with Streams
Stream<String> stream2 =
[Link](); ===================

} -> Filtering means getting required data from original


data
}

Ex: get only even numbers from given


===================
numbers
Stream Operations

===================
Ex: get emps whose salary is >=
1,00,000

-> Stream API provided several methods to perform


Operations on the data
Ex: Get Mobiles whose price is <=
15,000

-> We can divide Stream api methods into 2 types

1) Intermediate Operational -> To apply filter on the data, Stream api provided
Methods filter ( ) method

2) Terminal Operational Ex : Stream filter (Predicate p)


Methods
=================== }

Example - 1 : Filter

==================

==========================

Example - 2 : Filter

package [Link]; ========================

import [Link]; package [Link];

import [Link];

import [Link];

public class FirstDemo { import [Link];

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

List<Integer> list = [Link](66, public static void main(String[] args) {


32, 45, 12, 20);

List<String> names =
/*for (Integer i : list) { [Link]("John", "Anushka", "Anupama", "Smith",
"Ashok");
if (i > 20) {

[Link](i);
[Link]().filter(i ->
}
[Link]("A")).forEach(i -> [Link](i));
}*/

}
/*Stream<Integer> stream =
}
[Link]();

==================
Stream<Integer> filteredStrem =
[Link](i -> i > 20); Example - 3 : Filter

==================

[Link](i ->
[Link](i));*/
package [Link];

[Link]().filter(i -> i > 20).forEach(i


import [Link];
-> [Link](i));

public class FirstDemo {


}
[Link] = name;

public static void main(String[] args) { [Link] = age;

User u1 = new User("Anushka", 25);

User u2 = new User("Smith", 30); public String toString() {

User u3 = new User("Raju", 15); return "User [name=" + name + ",


age=" + age + "]";
User u4 = new User("Rani", 10);
}
User u5 = new User("Charles", 35);
}
User u6 = new User("Ashok", 30);

Stream<User> stream = [Link](u1,


u2, u3, u4, u5, u6); ===================

Mapping Operations

// [Link](u -> [Link] >= ===================


18).forEach(u -> [Link](u));

-> Mapping operations are belongs to intermediate


/*[Link](u -> [Link] >= operations in the Stream api
18 && [Link]("A"))

.forEach(u ->
-> Mapping operations are used to transform the
[Link](u));*/
stream elements and return transformed elements as
new Stream

[Link](u -> [Link] >= 18)

.filter(u ->
[Link]("A"))
Ex : Stream map (Function function) ;
.forEach(u ->
[Link](u));

}
=======================
}
Example-1 : map ( ) method

=======================
class User {

public class FirstDemo {


String name;

int age;
public static void main(String[] args) {

User(String name, int age) {


List<String> names =
[Link]("india","usa","uk", "japan"); //Akash - 5

/*for(String name : names) { [Link]()

.filter(name ->
[Link]([Link]()); [Link]("A"))

}*/ .map(name -> name + "-"


+[Link]())

.forEach(name ->
[Link]().map(name ->
[Link](name));
[Link]()).forEach(n ->
[Link](n)); }

[Link]().mapToInt(name ->
[Link]()).forEach(i -> [Link](i));

=======================
}
Example-3 : map ( ) method
}
========================

=========================
class Employee ( ) {
Example-2 : map ( ) method

========================
String name;

int age;
public class FirstDemo {
double salary;

public static void main(String[] args) {


}

Task : Print Emp Name with Emp age whose salary is


List<String> names = >= 50,000 using Stream API.
[Link]("Ashok", "Anil", "Raju", "Rani", "John",
"Akash", "Charles");

public class FirstDemo {


// print name with its length which
are starting with 'A' using Stream API

public static void main(String[] args) {


//Ashok - 5

//Anil
-4 Employee e1 = new Employee("John",
35, 55000.00);
Employee e2 = new
Employee("David", 25, 45000.00);
===================================
Employee e3 = new
Q) What is flatMap(Function f) method ?
Employee("Buttler", 35, 35000.00);
===================================
Employee e4 = new
Employee("Steve", 45, 65000.00);

-> It is used to flaten list of streams into single stream


Stream<Employee> stream =
[Link](e1, e2, e3, e4);

public class FirstDemo {


/*[Link](e -> [Link] >=
50000.00)

.map(e -> [Link]+" - " public static void main(String[] args) {


+[Link])

.forEach(e -> List<String> javacourses =


[Link](e));*/ [Link]("core java", "adv java", "springboot");

[Link](e -> [Link] >= List<String> uicourses =


50000.00) [Link]("html", "css", "bs", "js");
.forEach(e ->
[Link]([Link] + "-" + [Link]));
List<List<String>> courses =
[Link](javacourses, uicourses);
}

} //[Link]().forEach(c ->
[Link](c));

class Employee {
Stream<String> fms =
[Link]().flatMap(s -> [Link]());
String name;

int age;
[Link](c ->
double salary; [Link](c));

public Employee(String name, int age, double }


salary) {
}
[Link] = name;

[Link] = age;
==========================
[Link] = salary;
Slicing Operations with Stream
}
==========================
}
[Link]().distinct().forEach(name ->
1) distinct ( ) => To get unique elements from the
[Link](name));
Stream

}
2) limit ( long maxSize ) => Get elements from the
stream based on given size }

3) skip (long n) => It is used to skip given number of


elements from starting position of the stream
============================

Matching Operations with Stream

============================
Note: All the above 3 methods are comes under
Intermediate Operational Methods. They will perform
operation and returns new Stream. 1) boolean anyMatch (Predicate p )

2) boolean allMatch (Predicate p )


package [Link]; 3) boolean noneMatch (Predicate p )

import [Link]; Note: The above 3 methods are belongs to Terminal


Operations because they will do operation and they
import [Link];
will return result directley (they won't return stream)

public class FirstDemo {


-> The above methods are used to check the given
condition and returns true or false value based on
condition.
public static void main(String[] args) {

List<String> javacourses =
[Link]("corejava", "advjava", "springboot", package [Link];
"restapi", "microservices");

import [Link];
[Link]().limit(3).forEach(c
import [Link];
-> [Link](c));

public class FirstDemo {


[Link]().skip(3).forEach(c
-> [Link](c));

public static void main(String[] args) {


List<String> names =
[Link]("raja", "rani", "raja", "rani", "guru");
Person p1 = new Person("John",
"USA");
Person p2 = new Person("Steve", String country;
"JAPAN");

Person p3 = new Person("Ashok",


public Person(String name, String country) {
"INDIA");
[Link] = name;
Person p4 = new Person("Ching",
"CHINA"); [Link] = country;

}
List<Person> persons =
[Link](p1, p2, p3, p4);
}

boolean status1 =
[Link]().anyMatch(p -> ===================
[Link]("INDIA")); Collectors with Stream
[Link]("Any Indian ==================
Available ? :: " + status1);

-> Collectors are used to collect data from Stream


boolean status2 =
[Link]().anyMatch(p ->
[Link]("CANADA"));

[Link]("Any Canadian ===================


Available ? :: " + status2);
Example-1 : Collectors

===================
boolean status3 =
[Link]().allMatch(p ->
[Link]("INDIA"));
package [Link];
[Link]("All Persons from
India ? :: " + status3);
import [Link];

import [Link];
boolean status4 =
[Link]().noneMatch(p -> import [Link];
[Link]("MEXICO"));

[Link]("No Persons from


public class FirstDemo {
Mexico ? :: " + status4);

public static void main(String[] args) {


}

}
Person p1 = new Person("John",
"USA");
class Person {
Person p2 = new Person("Steve",
"JAPAN");

String name;
Person p3 = new Person("Ashok", }
"INDIA");

Person p4 = new Person("Ching",


}
"CHINA");

Person p5 = new Person("Kumar",


"INDIA"); ===================

Example-2: Collectors
List<Person> persons = ===================
[Link](p1, p2, p3, p4, p5);

package [Link];
List<Person> indians =
[Link]()
import [Link];
.filter(p -> import [Link];
[Link]("INDIA"))
import [Link];

.collect([Link]());
public class FirstDemo {

[Link](i ->
[Link](i)); public static void main(String[] args) {

} Person p1 = new Person("John",


} "USA");

Person p2 = new Person("Steve",


"JAPAN");
class Person {
Person p3 = new Person("Ashok",
"INDIA");
String name; Person p4 = new Person("Ching",
String country; "CHINA");

Person p5 = new Person("Kumar",


"INDIA");
public Person(String name, String country) {

[Link] = name;
List<Person> persons =
[Link] = country; [Link](p1, p2, p3, p4, p5);
}

// collect names of persons who are


belongs to india and store into names collection
@Override

public String toString() {


List<String> names = [Link]()
return "Person [name=" + name + ",
country=" + country + "]";
.filter(p ->
Mappings ----> map ( ) & flatMap ( )
[Link]("INDIA"))

.map(p -> [Link]) Slicing ----> distinct ( ) & limit () & skip ( )

.collect([Link]());

[Link](names);
============================================
} ==
} Set - 2 : Terminal Operations (will return result)

============================================
==
class Person {

Finding ---> findFirst ( ) & findAny ( )


String name;

String country;
Matching ---> anyMatch ( ) & allMatch ( ) &
noneMatch ( )
public Person(String name, String country) {

[Link] = name;
Collecting ---> collect ( )
[Link] = country;

@Override

public String toString() {

return "Person [name=" + name + ",


country=" + country + "]";

}
============

Requirement
}
===========

=> Write a java program to get MAX, MIN and AVG


============================================
salary from given employees data using Stream API.
==

Set - 1 : Intermediate Operations (will return Stream)

============================================
==

package [Link];
Filters ----> filter ( )
import [Link]; .collect([Link]([Link]
ng(e -> [Link])));
import [Link];

import [Link];
[Link]("Min Salary :: " +
import [Link];
[Link]().salary);
import [Link];

Double avgSalary =
public class FirstDemo { [Link]().collect([Link](e ->
[Link]));

[Link](avgSalary);
public static void main(String[] args) {
}

}
Employee e1 = new Employee(1,
"Robert", 26500.00);

Employee e2 = new Employee(2, class Employee {


"Abraham", 46500.00);
int id;
Employee e3 = new Employee(3,
String name;
"Ching", 36500.00);
double salary;
Employee e4 = new Employee(4,
"David", 16500.00);

Employee e5 = new Employee(5, public Employee(int id, String name, double


"Cathy", 25500.00); salary) {

[Link] = id;

List<Employee> list = [Link](e1, [Link] = name;


e2, e3, e4, e5);
[Link] = salary;

}
Optional<Employee> max =
}
[Link]()

====================
.collect([Link]([Link]
ng(e -> [Link]))); Group By using Stream

====================

[Link]("Max Salary :: " +


[Link]().salary); -> Group By is used categorize the data / Grouping the
data

Optional<Employee> min =
[Link]() -> When we use groupingBy ( ) function with stream
they it will group the data as Key-Value(s) pair and it
will return Map object
-> In below example employees will be grouped based class Employee {
on Country name.
int id;

String name;
package [Link];
double salary;

String country;
import [Link];

import [Link];
public Employee(int id, String name, double
import [Link]; salary, String country) {

import [Link]; [Link] = id;

[Link] = name;

public class FirstDemo { [Link] = salary;

[Link] = country;

public static void main(String[] args) { }

Employee e1 = new Employee(1,


"Robert", 26500.00, "USA");
================
Employee e2 = new Employee(2,
Parallel Streams
"Abraham", 46500.00, "INDIA");
===============
Employee e3 = new Employee(3,
"Ching", 36500.00, "CHINA");

Employee e4 = new Employee(4, -> Generally Streams will execute in sequence order
"David", 16500.00, "INDIA");

Employee e5 = new Employee(5,


"Cathy", 25500.00, "USA") ; -> To improve execution process of the stream we can
use parallel streams

List<Employee> list = [Link](e1,


e2, e3, e4, e5); -> Paralell Streams introduced to improve
performance of the program.

Map<String, List<Employee>> data =


[Link]()

.collect([Link](e -> [Link])); package [Link];

[Link](data); import [Link];


}

} public class ParallelDemo {


public static void main(String[] args) { -> Spliterator can't be used with Map implementation
classes

[Link]("====== Serial
Stream ========");

Stream<Integer> ss = [Link](1, 2, package [Link];


3, 4);

[Link](n -> [Link](n +


import [Link];
" :: " + [Link]()));
import [Link];

import [Link];
[Link]("====== Parallel
Strem =======");

Stream<Integer> ps = [Link](1, 2, public class ParallelDemo {


3, 4);

[Link]().forEach(n ->
[Link](n + " :: " + public static void main(String[] args) {
[Link]()));

} List<String> names =
} [Link]("sachin", "sehwag", "dhoni");

Spliterator<String> spliterator =
[Link]().spliterator();
==============

Java Spliterator
[Link](n ->
============== [Link](n));

}
-> Like Iterator and ListIterator, Spliterator is one of }
the Java Iterator

-> Spliterator introduced in java 1.8v

-> Spliterator is an interface in collections api


=============

Stream Reduce
-> Spliterator supports both serial & paralell
programming =============

-> Spliterator we can use to traverse both Collections package demo;


& Streams

import [Link];
public class Sum {

hello();

public static void main(String[] args) {

------------------------------------------------------

int[] nums = { 1, 2, 3, 4, 5 };

-> Open command prompt and execute below


command
/*int sum = 0;

for(int i : nums) {
syntax : jjs [Link]
sum = sum + i;

[Link](sum);*/
-> We can execute above Java Script file using Java
program like below
int reduce =
[Link](nums).reduce(0, (a,b) -> a+b);

[Link](reduce);
import [Link].*;

}
import [Link].*;
}

public class Demo {

public static void main(String... args) throws


======================
Exception {
Nashorn Engine in Java 1.8

======================
ScriptEngine se = new
ScriptEngineManager().getEngineByName("Nashorn");

-> Nashorn is a Java Script Engine which is used to


execute Java Script code using JVM
[Link](new FileReader("[Link]"));

}
-> Create a javascript file like below (filename : [Link])
}

--------------------- [Link] --------------------------


==========================

I/O Streams Changes in Java 8


var hello = function(){
==========================
print("Welcome to JavaScript");

}
Task : Write a java program to read a file data and
print it on the console
while (line != null) {

[Link](line);

line = [Link]();
-> To read file data we can use FileReader &
}
BufferedReader classes
[Link]();*/

String filename = "[Link]";


FileReader ----> It will read the
data character by character (slow performance)

try (Stream<String> stream =


[Link]([Link](filename))){
BufferedReader ---> It will
read the data line by line

[Link](line ->
[Link](line));
[Link](Path path) ---> It
will read all lines at a time and returns as a Stream

}catch(Exception e) {

[Link]();

}
package demo;
}

}
import [Link];

import [Link];

import [Link];

public class ReadFileData {


=======================

Java 8 Base64 Changes


public static void main(String[] args) throws
Exception { =======================

/*FileReader fr = new FileReader(new -> Base64 is a predefined class available in [Link]


File("[Link]")); package

BufferedReader br = new -> Base64 class providing methods to perform


BufferedReader(fr); encoding and decoding

String line = [Link]();


Encoder encoder =
[Link]();
// constructor

// getters and setters


// converting String to byte[] and
}
passing as input for encode( ) method

byte[] encode =
[Link]([Link]()); ============================================
==================

List<Employee> employeeList = new


// Converting byte[] to String
ArrayList<Employee>();
String encodedPwd = new
String(encode);
[Link](new Employee(1, "Jhansi", 32,
"Female", "HR", 2011, 25000.0));
[Link](encodedPwd);
[Link](new Employee(2, "Smith", 25,
"Male", "Sales", 2015, 13500.0));

Decoder decoder = [Link](new Employee(3, "David", 29,


[Link](); "Male", "Infrastructure", 2012, 18000.0));

[Link](new Employee(4, "Orlen", 28,


"Male", "Development", 2014, 32500.0));
byte[ ] decode =
[Link](encodedPwd); [Link](new Employee(5, "Charles", 27,
"Male", "HR", 2013, 22700.0));
String decodedPwd = new
String(decode); [Link](new Employee(6, "Cathy", 43,
"Male", "Security", 2016, 10500.0));
[Link](decodedPwd);
[Link](new Employee(7, "Ramesh", 35,
"Male", "Finance", 2010, 27000.0));

[Link](new Employee(8, "Suresh", 31,


================================ "Male", "Development", 2015, 34500.0));

Stream API Interview Questions [Link](new Employee(9, "Gita", 24,


"Female", "Sales", 2016, 11500.0));
================================
[Link](new Employee(10, "Mahesh", 38,
"Male", "Security", 2015, 11000.5));
class Employee [Link](new Employee(11, "Gouri", 27,
{ "Female", "Infrastructure", 2014, 15700.0));

int id; [Link](new Employee(12, "Nithin", 25,


"Male", "Development", 2016, 28200.0));
String name;
[Link](new Employee(13, "Swathi", 27,
int age; "Female", "Finance", 2013, 21300.0));
String gender; [Link](new Employee(14, "Buttler", 24,
String department; "Male", "Sales", 2017, 10700.5));

int yearOfJoining; [Link](new Employee(15, "Ashok", 23,


"Male", "Infrastructure", 2018, 12700.0));
double salary;
[Link](new Employee(16, "Sanvi", 26,
"Female", "Development", 2015, 28900.0));
Optional<Employee> optional =
[Link]()

.collect([Link]([Link]
1. How many male and female employees are there in
ngDouble(Employee::getSalary)));
the organization ?

if([Link]()) {

Employee employee =
Map<String, Long> map1 =
[Link]();
[Link]().collect([Link](Employe
e::getGender, [Link]()));
[Link](employee);
[Link](map1);
}

2. Print the name of all departments in the


organization ?

5. Get the names of all employees who have joined


after 2015 ?
[Link]()

.map(Employee::getDepartment) [Link]()

.distinct() .filter(e -> [Link] >


2015)
.forEach(name ->
[Link](name)); .map(e -> [Link])

.forEach(name ->
[Link](name));
3. What is the average age of male and female
employees ?

6. Count the number of employees in each


department ?
Map<String, Double> map =
[Link]()

Map<String, Long> map =


.collect([Link](Employee::getG [Link]()
ender, [Link](Employee::getAge)));

[Link](map);
.collect([Link](Employee::getD
epartment, [Link]()));

[Link](map);

4. Get the details of highest paid employee in the


7. What is the average salary of each department ?
organization ?
Map<String, Double> map = 10. How many male and female employees are there
[Link]() in the Sales team ?

.collect([Link](Employee::getD
Map<String, Long> map =
epartment,
[Link]()
[Link](Employee::getSalary)));

[Link](map);
.filter(e ->
[Link]().equals("Sales"))

8. Get the details of youngest male employee in the


Development department ?
.collect([Link](Employee::getG
ender, [Link]()));
Optional<Employee> optional =
[Link]()
[Link](map);
.filter(e ->
[Link]().equals("Male") &&
[Link]().equals("Development"))
11. What is the average salary of male and female
employees ?
.min([Link](Employee::getAg
e));
12. List down the names of all employees in each
department ?
if([Link]()) {

13. What is the average salary and total salary of the


[Link]([Link]());
whole organization ?
}

14. Separate the employees who are younger or


9. Who has the most working experience in the equal to 25 years from those employees who are older
organization ? than 25 years ?

Optional<Employee> optional = 15. Who is the oldest employee in the organization?


[Link]()

.collect([Link]([Link]
ng(Employee::getYearOfJoining)));

if([Link]()) {

[Link]([Link]());

You might also like