Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Collections JDK8 Features

Download as pdf or txt
Download as pdf or txt
You are on page 1of 81

Java Collections & JDK8

(Simplified)

SRINIVAS GARAPATI

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, AMEERPET, HYDERABAD
Contact for Online Classes: +91 – 911 955 6789 / 7306021113
Practice @ www.onlinejavacompiler.com

Contents
S No Topic Page Num
01 Introduction to Collection Framework 02
02 Wrapper classes 05
03 Generics 06
04 ArrayList 07
05 For-each loop 14
06 Iterator 16
07 ListIterator 17
08 List of Objects (Parameterized constructor approach) 18
09 List of Objects (POJO class approach) 25
10 ArrayList – Case Studies 28
11 ArrayList Operations – Menu driven approach 35
12 ArrayList Employee CRUD – Menu Driven 37
13 Vector 40
14 Stack 43
15 LinkedList 45
16 Set Interface 46
17 Map Interface 48
18 Comparator 55
19 Java8 Comparator 57
20 Java8 features 59
21 Static methods 61
22 Functional Interface 63
23 Lambda Expression 64
24 Method References 67
25 forEach() method 68
26 Stream API 70
27 Map() and Filter() 71
28 Collectors Class 73
29 Collections – Interview Questions 74
30 JDK8 – Interview Questions 77

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 1
Practice @ www.onlinejavacompiler.com

Collection Framework

Introduction:
 Programming languages and Technologies are used to develop applications.
 Applications are used in communication.
 Applications store and process information.

Banking Application –
Store customers information and transactions information.
Customers use Banking application to communicate with Banking Employee.

How to store information in application?


 We use variables of different data types to store information.
o Primitive type: Store only one value at a time.
o Array: Store more than one value but of same type
o Object: Store more than one value of different types
o Collection: Store multiple objects.

What are Data Structures? Use?


 Data structures are used to organize the data.
 We can perform operations quickly and easily on organized data.
 Data structures either Linear or Non-Linear.

Linear Data Structures: arrange the data sequentially in which elements are connected to its
previous and next adjacent.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 2
Practice @ www.onlinejavacompiler.com

Non-Linear Data Structures: in which one element connected to multiple elements and the
elements arranged in two-dimensional or multi-dimensional format.

Define Collection?
 Collection is a group of objects.
 Examples, List, Set, Queue, Map etc.

What is Collection framework?


 Collection Framework is a collection of interfaces and implemented classes.
 Collection Framework provides implementations of Data structures & Algorithms by
which we can store and process information without implementing them.

What is the need of storing group of objects?


 To store the record type information which is fetching from Database.
 To perform Different types of operations on group of objects like insertion, Deletion,
Updating, searching, sorting etc...
 Can set multiple objects to method as a parameter.
 Method can return multiple objects at a time after processing.

Collection Hierarchy: The following diagram represents interfaces and classes available in java
Collection Framework

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 3
Practice @ www.onlinejavacompiler.com

Define Array and Collection:


 Array is static – fixed size
 Collection is dynamic – size grows and shrinks with insertions and deletions.

Define List, Set and Map:


List Set Map
List is index based. Set is not index based. Map is not index based.
List allow duplicates. Set doesn’t allow duplicates. Map store elements using keys.
Keys must be unique.
Elements can be duplicated.

List implemented by:


1. ArrayList
a. Accessing elements much faster.
b. Insertions and Deletions are slower – shifting elements takes time.

2. Vector:
a. Accessing elements much faster.
b. Insertions and Deletions are slower – shifting elements takes time.

3. Stack:
a. Stack follows Last In First Out (LIFO) rule.
b. Inserting and removing elements from one end called TOP.

4. LinkedList:
a. Accessing element slower, nodes-based access.
b. Insertions and Deletions are faster – No shifting of elements.

Set implemented by:


1. HashSet: doesn’t maintain insertion order.
2. LinkedHashSet: maintains insertion order.
3. TreeSet: maintains sorted order.

Map implemented by:


1. Hashtable: maintains sorted order using keys. Null keys not allowed.
2. HashMap: doesn’t maintain insertion order. One null key allowed.
3. LinkedHashMap: maintain insertion order. One null key allowed.
4. TreeMap: maintain sorted order using keys. Null keys not allowed.

Queue implemented by:


PriorityQueue: It is not an order collection and allow duplicates. Priority queue elements
are retrieved in sorted order. Head of the priority queue will be the smallest element.
Once this element is retrieved, the next smallest element will be the head of the queue.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 4
Practice @ www.onlinejavacompiler.com

Wrapper classes in Collections

Wrapper classes:
 Collection stores only objects (not primitive data).
 Wrapper classes providing functionality to perform conversions like
o Primitive -> Object (Boxing)
o Object -> Primitive (Un boxing)
 These conversions become automated since JDK5

Note: for every primitive type there is a wrapper class in java

Primitive type Wrapper class


byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean

Boxing: Conversion of primitive type into object type


int x = 10;
Integer obj = new Integer(x);

Un boxing: Conversion of object type into primitive type


int x = obj.intValue();

Auto Boxing: Auto conversion of boxing


int x = 10;
Integer obj = x;

Auto Un boxing: Auto conversion process of un boxing.


int x = obj;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 5
Practice @ www.onlinejavacompiler.com

Generics

Generics:
 As we know, collection only store objects.
 Generics introduced in JDK5.
 Generics are used to specify what type of objects allowed to store into Collection.

Collection without Generics: Allow to store any type of Objects.


Syntax:
Collection c = new Collection();
c.add(10);
c.add(23.45);
c.add(“java”);

Collection with Generics: Allow only specific type of data Objects.


Syntax:
Collection<Integer> c = new Collection<Integer>();
c.add(10);
c.add(“java”); // Error :

Collection with Generics that allows any type of object:


Syntax:
Collection<Object> c = new Collection<Object>();
c.add(10);
c.add(“java”);
c.add(23.45);

Note: Object is the super class of all classes in Java

If we store information in Object form, we need to downcast the object into


corresponding type to perform operations.

For Example,
Collection<Object> c = new Collection<Object>();
c.add(10);

Downcast to Integer:
Integer x = c.get(0);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 6
Practice @ www.onlinejavacompiler.com

ArrayList Collection

ArrayList:
 ArrayList is an ordered collection and allow duplicates.
 ArrayList is index based.
 Processing elements much faster (index based)
 Insertions and Deletions are slower (shifting of elements takes time)

Methods:
Name Description
int size() Returns the number of elements in this list.
boolean add(E e) Appends the specified element to the end of this list
Object remove(int index) Removes the element at the specified position in this list
void clear() Removes all of the elements from this list
void add(int index, E element) Inserts element at the specified position in this list
Object get(int index) Returns the element at the specified position in this list
boolean isEmpty() Returns true if this list contains no elements
Object set(int index, E element) Replaces the element at the specified position in this list
with the specified element
boolean contains(Object o) Returns true if this list contains the specified element
int indexOf(Object o) Returns the index of the first occurrence of the specified
element, or -1 if this list does not contain the element.
Iterator<Object> iterator() Returns an iterator over the elements in this list
boolean addAll(Collection c) Appends all of the elements in the specified collection to
the end of this list
Object clone() Returns a shallow copy of this ArrayList instance
ListIterator listIterator(int index) Returns a list iterator over the elements in this list (in
proper sequence), starting at the specified position in
the list.
Object[] toArray() Returns an array containing all of the elements in this list
in proper sequence (from first to last element).

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 7
Practice @ www.onlinejavacompiler.com

Program to display ArrayList and its size:


 add() method is used to append element to the list.
 size() method returns the length of list.
import java.util.*;
class Code {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
System.out.println("List is : " + list);
System.out.println("Size is : " + list.size());
}
}

Program to check the list is empty or not:


 isEmpty() method returns true if the list doesn’t contains elements else returns false
import java.util.*;
class Code {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
if(list.isEmpty())
System.out.println("List is empty");
else
System.out.println("List contains elements");
}
}

Program to display the element of specified index:


 get(int index) returns the element of specified index.
import java.util.*;
class Code{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 8
Practice @ www.onlinejavacompiler.com

for (int i=10 ; i<=50 ; i+=10){


list.add(i);
}
System.out.println("List is : " + list);
System.out.println("Enter index to display value : ");
int loc = sc.nextInt();
System.out.println("Element @ index-" + loc + " is : " + list.get(loc));
}
}

We specify the error message – if the index value is not present:


if(loc>=0 && loc<=list.size()-1){ try{
System.out.println(list.get(loc)); System.out.println(list.get(loc));
} }
else{ catch(IndexOutOfBoundsException e){
System.out.println("Invalid index"); System.out.println("Invalid index");
} }

Insert element into specified index: add(int index, E e) method is used to insert element into
specified index.
Instructions to code:
 Create ArrayList with 5 elements 10, 20, 30, 40, 50
 Read index to insert.
 Check whether the index is present or not
 If the index is present, then read the value and insert.
 If the index is not present, display Error message.
import java.util.*;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
System.out.println("List is : " + list);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 9
Practice @ www.onlinejavacompiler.com

System.out.print("Enter index to insert : ");


int loc = sc.nextInt();
if(loc>=0 && loc<list.size()){
System.out.print("Enter element to insert : ");
int ele = sc.nextInt();
list.add(loc, ele);
System.out.println("List is : " + list);
}
else{
System.out.println("Invalid index");
}
}
}

Program to remove all elements from the list: clear() method removes all elements from the
list.
Instructions to code:
 Create list with 5 elements.
 Display – List is not empty
 Remove all elements using clear() method
 Display – List is empty.
import java.util.*;
class Code
{
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
list.add(i);

System.out.println("List is : " + list);


if(list.isEmpty())
System.out.println("List is empty");
else
System.out.println("List is not empty");

list.clear();
System.out.println("List is : " + list);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 10
Practice @ www.onlinejavacompiler.com

if(list.isEmpty())
System.out.println("List is empty");
else
System.out.println("List is not empty");
}
}

Program to remove index element: remove(int index) method removes element of specified
index.
Instructions to code:
 Create list with elements
 Read index value.
 If the index is valid – remove the element and display list
 If the index is not valid – display error message.
import java.util.*;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++){
list.add(i);
}
System.out.println("List is : " + list);

System.out.print("Enter index to remove : ");


int loc = sc.nextInt();
if(loc>=0 && loc<list.size()){
list.remove(loc);
System.out.println("List is : " + list);
}
else{
System.out.println("Error : No such index to remove");
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 11
Practice @ www.onlinejavacompiler.com

Program to check whether the list contains element or not: contains() method returns true if
the list has specified element.
import java.util.*;
class Code{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
list.add(i);
System.out.println("List is : " + list);
System.out.print("Enter element to check in list : ");
int ele = sc.nextInt();
if(list.contains(ele))
System.out.println("Yes element is present in list");
else
System.out.println("No such element in list");
}
}
Program display the index value of element: indexOf() method returns index of specified
element. It returns -1 if no such element in the list.
import java.util.*;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
list.add(i);
System.out.println("List is : " + list);
System.out.print("Enter element to find index value : ");
int ele = sc.nextInt();
int index = list.indexOf(ele);
if(index!=-1)
System.out.println("Index value is : " + index);
else
System.out.println("No such element in list");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 12
Practice @ www.onlinejavacompiler.com

Program to replace the existing value: set(int index, E e) method replace the index element
with specified element.

Instructions to code:
 Create ArrayList with elements.
 Read the element to replace
 Check the element is present or not in the list using contains() method.
 If the element is present,
o Read the new element to replace with.
 If the element is not present,
o Display error message.

import java.util.*;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++){
list.add(i);
}
System.out.println("List is : " + list);
System.out.print("Enter element to replace : ");
int x = sc.nextInt();
if(list.contains(x)) {
System.out.print("Enter new element : ");
int y = sc.nextInt();

int loc = list.indexOf(x);


list.set(loc, y);
System.out.println("Updated list : " + list);
}
else
System.out.println("No such element in list");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 13
Practice @ www.onlinejavacompiler.com

For-each loop:
 It is also called enhanced for loop.
 It is since JDK5
 For-each loop provides easy syntax to process elements of Array or Collection.

Limitations:
 For-each loop can process elements only in forward direction.
 For-each loop can process elements one by one only.

Syntax:
for (datatype var : Array/Collection ) {
statements ;
}

Program to display ArrayList using for-each loop:


import java.util.*;
class Code {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
list.add(i*5);

System.out.println("List is : ");
for(Integer x : list)
System.out.println(x);
}
}
Display ArrayList element by element using for-loop: get(int index) method is used to
retrieve each element using its index.
import java.util.*;
class Code {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
list.add(i*5);

System.out.println("List is : ");
for(int i=0 ; i<=list.size()-1 ; i++)
System.out.println(list.get(i));
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 14
Practice @ www.onlinejavacompiler.com

Program to display ArrayList in Reverse Order:


import java.util.*;
class Code
{
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
list.add(i*5);

System.out.println("List is : ");
for(int i=list.size()-1 ; i>=0 ; i--)
System.out.println(list.get(i));
}
}

Program to Merge 2 ArrayLists: addAll(Collection c) method is used to merge 2 lists.


import java.util.*;
class Code
{
public static void main(String[] args) {
List<Integer> a1 = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
a1.add(i*5);
System.out.println("a1 list is : " + a1);

List<Integer> a2 = new ArrayList<Integer>();


for(int i=5 ; i>=1 ; i--)
a2.add(i*5);
System.out.println("a1 list is : " + a1);

a1.addAll(a2);
System.out.println("a1 list after merge : " + a1);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 15
Practice @ www.onlinejavacompiler.com

Iterator:
 It is an interface.
 Iterator providing methods to iterator any collection.
 iterator() method returns Iterator object of any collection.

Methods:
1. boolean hasNext(): checks the next element is present or not to iterate.
2. Object next(): returns the next element of iterator object.

Program to display ArrayList using Iterator:


import java.util.*;
class Code
{
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++)
list.add(i*5);

System.out.println("Display using Iterator :");


Iterator<Integer> itr = list.iterator();
while(itr.hasNext())
{
Integer ele = itr.next();
System.out.println(ele);
}
}
}

When we use for/for-each/iterator?


For-loop For-each loop Iterator
Index based. Not index based. Not index based.
Process only List(index based) Process List, Set and Map Process List, Set and Map
Use get(index) method Do not use any other method Do not use any other method

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 16
Practice @ www.onlinejavacompiler.com

ListIterator:
 It is an interface
 listIterator() method returns ListIterator object.
 Using ListIterator, we can iterate elements,
o In Forward direction
o In Backward direction
o From specified index value

Iterator List in Forward Direction using hasNext() and next() methods:


List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++){
list.add(i*5);
}
ListIterator<Integer> itr = list.listIterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}

Iterator List in Backward Direction using hasPrevious() and previous() methods:


List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=5 ; i++){
list.add(i*5);
}
ListIterator<Integer> itr = list.listIterator(list.size());
while(itr.hasPrevious())
{
System.out.println(itr.previous());
}

Display list from specified index value:


List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=10 ; i++){
list.add(i*5);
}
ListIterator<Integer> itr = list.listIterator(5);
while(itr.hasNext())
{
System.out.println(itr.next());
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 17
Practice @ www.onlinejavacompiler.com

List of Employee Objects


(Parameterized constructor approach)
List of Objects:
 Collections are mainly used to store and process information of Employees, Students,
Customers, Products, Books, Accounts etc.
 Object is a set of dissimilar elements. For example, Employee has ID, Name and Salary.
 We create objects with details and store the object into collection as follows.

Program to create and display List of Employees:


1. Employee.java: contains Employee class
2. Main.java: contains code of creating ArrayList with Employees and display.

Approach1: (Create 3 employee objects directly and add to list)


Employee.java:
 Create Employee class with instance variables id, name, salary
 Define parameterized constructor to initialize the object.
class Employee {
int id;
String name;
double salary;
Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}

Main.java:
 Create 3 Employee objects and add to List
 Display details using for-each loop

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 18
Practice @ www.onlinejavacompiler.com

import java.util.*;
class Main {
public static void main(String[] args) {
List<Employee> list = new ArrayList<Employee>();

Employee e1 = new Employee(101, "Amar", 35000);


Employee e2 = new Employee(102, "Harin", 45000);
Employee e3 = new Employee(103, "Satya", 40000);
list.add(e1);
list.add(e2);
list.add(e3);
System.out.println("Details are : ");
for(Employee e : list)
{
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}
}
}

You can directly add objects to the list as follows:


import java.util.*;
class Main {
public static void main(String[] args) {
List<Employee> list = new ArrayList<Employee>();

list.add(new Employee(101, "Amar", 35000));


list.add(new Employee(102, "Harin", 45000));
list.add(new Employee(103, "Satya", 40000));

System.out.println("Details are : ");


for(Employee e : list)
{
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 19
Practice @ www.onlinejavacompiler.com

Display using for loop:


System.out.println("Details are : ");
for(int i=0 ; i<=list.size()-1 ; i++)
{
Employee e = list.get(i);
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}

Display Employees List in reverse order:


 We must use for() loop to iterate in reverse order.
 For-each loop can move only in forward direction.

System.out.println("Details are : ");


for(int i=list.size()-1 ; i>=0 ; i--)
{
Employee e = list.get(i);
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}

Display using Iterator:


System.out.println("Details are : ");
Iterator<Employee> itr = list.iterator();
while(itr.hasNext())
{
Employee e = itr.next();
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}

Display reverse list using ListIterator:


System.out.println("Details are : ");
ListIterator<Employee> itr = list.listIterator(list.size());
while(itr.hasPrevious())
{
Employee e = itr.previous();
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 20
Practice @ www.onlinejavacompiler.com

Approach-2: (Create Employee objects by collecting details from arrays)


Employee.java:
 Create Employee class with instance variables id, name, salary
 Define parameterized constructor to initialize the object.
class Employee {
int id;
String name;
double salary;
Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}

Main.java:
 Collect values from Arrays to create Employee objects.
 Display details using for-each loop
import java.util.*;
class Main {
public static void main(String[] args) {
int[] ids = {101, 102, 103, 104, 105};
String[] names = {"Amar", "Annie", "Harini", "Satya", "Jai"};
double[] salaries = {23000, 56000, 43000, 48000, 16000};

List<Employee> list = new ArrayList<Employee>();


for (int i=0 ; i<=ids.length-1 ; i++){
Employee e = new Employee(ids[i], names[i], salaries[i]);
list.add(e);
}

System.out.println("Details are : ");


for(Employee e : list){
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 21
Practice @ www.onlinejavacompiler.com

Approach-3: (Read details using Scanner class)


Employee.java:
class Employee {
int id;
String name;
double salary;
Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}

Main.java: Create List with 5 Employee details by reading through Scanner.


import java.util.*;
class Main
{
public static void main(String[] args)
{
List<Employee> list = new ArrayList<Employee>();
Scanner sc = new Scanner(System.in);

System.out.println("Enter 5 Employee details : ");


for (int i=1 ; i<=5 ; i++)
{
System.out.println("Enter Emp-" + i + " details : ");
int id = sc.nextInt();
String name = sc.next();
double salary = sc.nextDouble();
Employee e = new Employee(id, name, salary);
list.add(e);
}

System.out.println("Details are : ");


for(Employee e : list)
{
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 22
Practice @ www.onlinejavacompiler.com

Approach-4: (Store objects to list until user quits)


Employee.java:
 Create Employee class with instance variables id, name, salary
 Define parameterized constructor to initialize the object.

Main.java: Read and Add employee details until end user quits.
import java.util.*;
class Main
{
public static void main(String[] args)
{
List<Employee> list = new ArrayList<Employee>();
Scanner sc = new Scanner(System.in);

while(true)
{
System.out.println("Enter Emp details to add : ");
int id = sc.nextInt();
String name = sc.next();
double salary = sc.nextDouble();
Employee e = new Employee(id, name, salary);
list.add(e);

System.out.print("Do you want to add another record(yes/no) : ");


String choice = sc.next();
if(choice.equals("no"))
{
break;
}
}

System.out.println("Details are : ");


for(Employee e : list)
{
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 23
Practice @ www.onlinejavacompiler.com

Approach-5: (Using BufferedReader class)


Employee.java:
 Create Employee class with instance variables id, name, salary
 Define parameterized constructor to initialize the object.

Main.java: Read and Add employee details until end user quits using BufferedReader.
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
List<Employee> list = new ArrayList<Employee>();
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter Emp details to add : ");
int id = Integer.parseInt(br.readLine());
String name = br.readLine();
double salary = Double.parseDouble(br.readLine());
Employee e = new Employee(id, name, salary);
list.add(e);

System.out.print("Do you add another record(yes/no) : ");


String choice = br.readLine();
if(choice.equals("no"))
{
break;
}
}

System.out.println("Details are : ");


for(Employee e : list) {
System.out.println(e.id + " , " + e.name + " , " + e.salary);
}
}
finally{
if(br!=null)
br.close();
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 24
Practice @ www.onlinejavacompiler.com

List of Employee Objects


(POJO class approach)

POJO class: (Plain Old Java Object)


 POJO rules are:
o Class is public
o Variables are private
o Every variable has get() and set() methods.

Approach1: (Construct objects from Arrays)

Employee.java: Create Employee POJO class


public class Employee
{
private int id;
private String name;
private double salary;
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public double getSalary() {
return this.salary;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 25
Practice @ www.onlinejavacompiler.com

Main.java:
 Create List to store Employee objects.
 Create objects from Arrays and add to List.
import java.util.*;
class Main
{
public static void main(String[] args) {
int[] ids = {101, 102, 103, 104};
String[] names = {"Amar", "Annie", "Harin", "Satya"};
double[] salaries = {35000, 45000, 40000, 38000};

List<Employee> list = new ArrayList<Employee>();


for (int i=0 ; i<=ids.length-1 ; i++) {
Employee e = new Employee();
e.setId(ids[i]);
e.setName(names[i]);
e.setSalary(salaries[i]);
list.add(e);
}

System.out.println("Details are : ");


for(Employee e : list) {
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary());
}
}
}

Approach2: (Construct objects by reading using Scanner)


import java.util.*;
class Main
{
public static void main(String[] args) {
List<Employee> list = new ArrayList<Employee>();
Scanner sc = new Scanner(System.in);

while(true)
{

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 26
Practice @ www.onlinejavacompiler.com

System.out.println("Enter Emp details : ");


int id = sc.nextInt();
String name = sc.next();
double salary = sc.nextDouble();

Employee e = new Employee();


e.setId(id);
e.setName(name);
e.setSalary(salary);

list.add(e);

System.out.print("Want to add one more(y/n) :");


if(sc.next().charAt(0) == 'n')
{
break;
}
}

System.out.println("Details are : ");


for(Employee e : list)
{
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary());
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 27
Practice @ www.onlinejavacompiler.com

ArrayList – Case Studies


Write code for following instructions:
 Define Employee POJO with variables id, name, salary, dept, location.
 Create an ArrayList of Employee type and store following values from arrays.
Id Name Salary Dept Location
101 Amar 30000 20 Hyderabad
102 Hareen 35000 10 Chennai
103 Sathya 40000 20 Bangalore
104 Annie 45000 20 Hyderabad
105 Raji 42000 30 Pune
106 Harsha 50000 10 Bangalore
Employee.class:
class Employee {
private int id;
private String name;
private double salary;
private int dept;
private String location;
int getId(){
return this.id;
}
String getName(){
return this.name;
}
double getSalary(){
return this.salary;
}
int getDept(){
return this.dept;
}
String getLocation(){
return this.location;
}
void setId(int id){
this.id = id;
}
void setName(String name){
this.name = name;
}
void setSalary(double salary){
this.salary = salary;
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 28
Practice @ www.onlinejavacompiler.com

void setDept(int dept){


this.dept = dept;
}
void setLocation(String location){
this.location = location;
}
}

Main.java:
import java.util.*;
class Main {
public static void main(String[] args) {
int[] ids = {101, 102, 103, 104, 105, 106};
String[] names = {"Amar", "Hareen", "Sathya", "Annie", "Raji", "Harsha"};
double[] salaries = {30000, 35000, 40000, 45000, 42000, 50000};
int[] depts = {20, 10, 20, 20, 30, 10};
String[] locations = {"Hyderabad", "Chennai", "Bangalore", "Hyderabad",
"Pune", "Bangalore"};

List<Employee> list = new ArrayList<Employee>();


for (int i=0 ; i<=ids.length-1 ; i++) {
Employee e = new Employee();
e.setId(ids[i]);
e.setName(names[i]);
e.setSalary(salaries[i]);
e.setDept(depts[i]);
e.setLocation(locations[i]);
list.add(e);
}
System.out.println("Details are : ");
for(Employee e : list)
{
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() +
" , " + e.getDept() + " , " + e.getLocation());
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 29
Practice @ www.onlinejavacompiler.com

Display details using for loop:


for(int i=0 ; i<=list.size()-1 ; i++)
{
Employee e = list.get(i);
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
}

Display details in reverse order:


for(int i=list.size()-1 ; i>=0 ; i--)
{
Employee e = list.get(i);
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
}

Display Employee details whose ID is 103:


boolean found=false;
for(Employee e : list)
{
if(e.getId() == 103)
{
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
found = true;
break;
}
}
if(!found)
{
System.out.println("ID 103 doesn't exist");
}

Display Employee details belongs to Hyderabad:


int count=0;
for(Employee e : list)
{

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 30
Practice @ www.onlinejavacompiler.com

if(e.getLocation().equals("Hyderabad"))
{
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
count++;
}
}
if(count==0)
{
System.out.println("No employee belongs to Hyderabad");
}

Display Employee details belongs in department 20 or 30:


int count=0;
for(Employee e : list)
{
if(e.getDept()==20 || e.getDept()==30)
{
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
count++;
}
}
if(count==0)
{
System.out.println("No employee belongs depts 20 or 30");
}

Display employee details those who not belongs to Hyderabad.


int count=0;
for(Employee e : list)
{
if(!(e.getLocation().equals("Hyderabad")))
{
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
count++;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 31
Practice @ www.onlinejavacompiler.com

}
}
if(count==0)
{
System.out.println("No employee records founds");
}

Display details belongs to department 20 and not belongs to Hyderabad:


int count=0;
for(Employee e : list)
{
if(e.getDept()==20 && !(e.getLocation().equals("Hyderabad")))
{
System.out.println(e.getId() + " ," + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
count++;
}
}
if(count==0)
{
System.out.println("No employee records founds");
}

Count how many employees working in both Hyderabad and Bangalore locations:
int count=0;
for(Employee e : list)
{
String loc = e.getLocation();
if(loc.equals("Hyderabad") || loc.equals("Bangalore"))
{
count++;
}
}
System.out.println("Count is : " + count);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 32
Practice @ www.onlinejavacompiler.com

Check the Employee with name “Amar” present or not:


boolean found=false;
for(Employee e : list)
{
if(e.getName().equals("Amar"))
{
System.out.println("Found with ID : " + e.getId());
found=true;
break;
}
}
if(!found)
{
System.out.println("Amar not present");
}

Display details whose salary greater than 35000:


int count=0;
for(Employee e : list)
{
if(e.getSalary()>35000)
{
System.out.println(e.getId() + " , " + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
count++;
}
}
if(count==0)
{
System.out.println("No employee found");
}

Display details whose salary between 30000 and 40000:


int count=0;
for(Employee e : list)
{
if(e.getSalary()>30000 && e.getSalary()<40000)

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 33
Practice @ www.onlinejavacompiler.com

{
System.out.println(e.getId() + " , " + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
count++;
}
}
if(count==0)
{
System.out.println("No employee found");
}

Display details whose salary below 40000 and not belongs to Hyderabad:
int count=0;
for(Employee e : list)
{
if(e.getSalary()<40000 && !(e.getLocation().equals("Hyderabad")))
{
System.out.println(e.getId() + " , " + e.getName() + " , " + e.getSalary() + " , " +
e.getDept() + " , " + e.getLocation());
count++;
}
}
if(count==0)
{
System.out.println("No employee found");
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 34
Practice @ www.onlinejavacompiler.com

ArrayList Operations – Menu Driven Approach

Following program explains how to perform ArrayList operations such as Append, Insert,
Replace, Update, Remove, Sort, Reverse and Display:
import java.util.*;
class Main
{
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("1.Append \n2.Insert \n3.Replace \n4.Remove
\n5.Display \n6.Sort \n7.Reverse \n8.Quit");

System.out.print("Enter choice : ");


int ch = sc.nextInt();
if(ch==1){
System.out.print("Enter element to append : ");
int ele = sc.nextInt();
list.add(ele);
System.out.println("Element added");
}
else if(ch==2){
System.out.print("Enter index : ");
int index = sc.nextInt();

if(index>=0 && index<=list.size()-1){


System.out.print("Enter element : ");
int ele = sc.nextInt();
list.add(index, ele);
System.out.println("Element inserted");
}
else
System.out.println("No such location");
}
else if(ch==3){
System.out.print("Enter element to replace : ");
int ele = sc.nextInt();

if(list.contains(ele)){
int index = list.indexOf(ele);
System.out.print("Enter new element : ");

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 35
Practice @ www.onlinejavacompiler.com

int x = sc.nextInt();
list.set(index, x);
System.out.println("Element replaced");
}
else
System.out.println("No such element in list");
}
else if(ch==4){
System.out.print("Enter element to remove : ");
int ele = sc.nextInt();
if(list.contains(ele)){
int index = list.indexOf(ele);
list.remove(index);
System.out.println("Element removed");
}
else
System.out.println("No such element to remove");
}
else if(ch==5){
if(list.isEmpty())
System.out.println("Empty list");
else
System.out.println("List is : " + list);
}
else if(ch==6){
Collections.sort(list);
System.out.println("List sorted");
}
else if(ch==7){
Collections.reverse(list);
System.out.println("List reversed");
}
else if(ch==8){
System.out.println("End");
System.exit(1);
}
else
System.out.println("Invalid choice");
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 36
Practice @ www.onlinejavacompiler.com

ArrayList – Employee CRUD – Menu Driven Approach

This program explains how to add employee details, display details of specific ID, remove
employee and update the details of employee:

import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
List<Employee> list = new ArrayList<Employee>();
while(true){
System.out.println("1.Add Record");
System.out.println("2.Display Record");
System.out.println("3.Display All");
System.out.println("4.Update Record");
System.out.println("5.Delete Record");
System.out.println("6.Exit");

System.out.print("Enter choice : ");


int ch = sc.nextInt();

if(ch==1){
System.out.println("Enter details :");
int id = sc.nextInt();
String name = sc.next();
double salary = sc.nextDouble();

Employee e=new Employee(id,name,salary);


list.add(e);
System.out.println("Record Added");
}
else if(ch==2){
if(list.isEmpty()){
System.out.println("empty list");
}
else{
System.out.print("Enter id : ");
int id = sc.nextInt();

boolean found=false;
for(Employee e : list){
if(e.id == id){
System.out.println("Name : " + e.name);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 37
Practice @ www.onlinejavacompiler.com

System.out.println("Salary : " + e.salary);


found = true;
break;
}
}
if(!found)
System.out.println("Invalid ID");
}
}
else if(ch==3){
if(list.isEmpty()){
System.out.println("Empty list");
}
else{
System.out.println("Details : ");
for(Employee e : list){
System.out.println("Name : " + e.name);
System.out.println("Salary : " + e.salary);
}
}
}
else if(ch==4){
if(list.isEmpty()){
System.out.println("Empty list");
}
else{
System.out.print("Enter id : ");
int id = sc.nextInt();

boolean found=false;
for(Employee e : list){
if(e.id == id){
System.out.print("Enter sal to update: ");
double salary = sc.nextDouble();
e.salary = salary;
System.out.println("Record updated");
found = true;
break;
}
}
if(!found)
System.out.println("Invalid ID");
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 38
Practice @ www.onlinejavacompiler.com

}
else if(ch==5){
if(list.isEmpty())
{
System.out.println("Empty list");
}
else
{
System.out.print("Enter id : ");
int id = sc.nextInt();

boolean found=false;
for(Employee e : list)
{
if(e.id == id)
{
int index = list.indexOf(e);
list.remove(index);
System.out.println("Removed");
found = true;
break;
}
}
if(!found)
System.out.println("Invalid ID");
}
}
else if(ch==6){
System.out.println("End");
System.exit(1);
}
else
{
System.out.println("Invalid choice");
}
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 39
Practice @ www.onlinejavacompiler.com

Vector:
 Vector implements List.
 Vector allow duplicates and follow insertion order.
 Vector is synchronized by default.
import java.util.*;
class Code
{
public static void main(String[] args)
{
Vector<Integer> v = new Vector<Integer>();
for (int i=1 ; i<=5 ; i++){
v.add(i*5);
}
System.out.println("Vector : " + v);
}
}

Enumeration:
 Vector is legacy(old) class since first version of JDK.
 Enumeration interface used to process vector element by element.
 elements() method of Vector class returns Enumeration-interface.

Methods of Enumeration:
1. hasMoreElements(): is used to check the element is present or not in Enumeration
2. nextElement(): returns the next element in the enumeration.
import java.util.*;
class Code
{
public static void main(String[] args)
{
Vector<Integer> v = new Vector<Integer>();
for (int i=1 ; i<=5 ; i++){
v.add(i*5);
}
System.out.println("Vector : ");
Enumeration<Integer> en = v.elements();
while(en.hasMoreElements())
{
Integer x = en.nextElement();
System.out.println(x);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 40
Practice @ www.onlinejavacompiler.com

ArrayList is not Synchronized: We get odd results when we try to add elements into ArrayList
from multiple threads.
import java.util.*;
class Test
{
static ArrayList<Integer> list = new ArrayList<Integer>();
}
class First extends Thread
{
public void run(){
for (int i=1 ; i<=100000 ; i++)
{
Test.list.add(i);
}
}
}
class Second extends Thread
{
public void run(){
for (int i=1 ; i<=100000 ; i++)
{
Test.list.add(i);
}
}
}
class Code
{
public static void main(String[] args) throws Exception {
First f = new First();
Second s = new Second();
f.start();
s.start();
f.join();
s.join();
System.out.println("List size is : " + Test.list.size());
}
}

Output: List size is : 166987

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 41
Practice @ www.onlinejavacompiler.com

Vector is synchronized by default: Vector is thread safe, hence we get perfect results when we
try to add elements from multiple threads
import java.util.*;
class Test
{
static Vector<Integer> list = new Vector<Integer>();
}
class First extends Thread
{
public void run(){
for (int i=1 ; i<=100000 ; i++)
{
Test.list.add(i);
}
}
}
class Second extends Thread
{
public void run(){
for (int i=1 ; i<=100000 ; i++)
{
Test.list.add(i);
}
}
}
class Code
{
public static void main(String[] args) throws Exception
{
First f = new First();
Second s = new Second();
f.start();
s.start();
f.join();
s.join();
System.out.println("Vector size is : " + Test.list.size());
}
}

Output: Vector size is : 200000

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 42
Practice @ www.onlinejavacompiler.com

Stack
Stack:
 Stack is an extension of Vector class.
 It follows LIFO – Last In First Out Rule

Methods are:
1. boolean empty() : Tests the stack is empty or not
2. Object peek(): returns the top element of stack but not remove
3. Object pop(): returns the top element of stack and removes
4. void push(Object e): push element on to the stack

import java.util.*;
class Code
{
public static void main(String[] args) throws Exception {
Stack<Integer> stk = new Stack<Integer>();
stk.push(10);
stk.push(20);
stk.push(30);
stk.push(40);
System.out.println("Stack is : " + stk);

System.out.println("Pop : " + stk.pop());


System.out.println("Pop : " + stk.pop());
System.out.println("Stack is : " + stk);

stk.push(50);
stk.push(60);
System.out.println("Stack is : " + stk);

System.out.println("Peek : " + stk.peek());


System.out.println("Peek : " + stk.peek());
System.out.println("Stack is : " + stk);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 43
Practice @ www.onlinejavacompiler.com

Stack Operations – Menu Driven Program


import java.util.*;
class Code {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
Stack<Integer> stk = new Stack<Integer>();
while(true){
System.out.println("1.Push \n2.Pop \n3.Display \n4.Peek \n5.Quit");
System.out.print("Enter choice : ");
int ch = sc.nextInt();
if(ch==1){
System.out.print("Enter element to push : ");
int ele = sc.nextInt();
stk.push(ele);
System.out.println("Element Pushed");
}
else if(ch==2){
if(stk.empty())
System.out.println("Empty stack");
else
System.out.println("Pop : " + stk.pop());
}
else if(ch==3){
if(stk.empty())
System.out.println("Empty stack");
else
System.out.println("Stack is : " + stk);
}
else if(ch==4){
if(stk.empty())
System.out.println("Empty stack");
else
System.out.println("Peek : " + stk.peek());
}
else if(ch==5){
System.out.println("End");
System.exit(1);
}
else
System.out.println("Invalid choice");
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 44
Practice @ www.onlinejavacompiler.com

Linked List
LinkedList:
 LinkedList implements List
 LinkedList allow duplicates and ordered collection.
 Linked List store elements in the form of nodes and connect with links.

 Accessing elements – slower in LinkedList


 Insertions and Deletions are faster – no shifting of elements.

Methods are:
boolean add(E e) Appends the specified element to the end of this list.
void add(int index, E element) Inserts the specified element at the specified position
void addFirst(E e) Inserts the specified element at the beginning of this list.
void addLast(E e) Appends the specified element to the end of this list.
void clear() Removes all of the elements from this list.
boolean contains(Object o) Returns true if this list contains the specified element.
E get(int index) Returns the element at the specified position in this list.
E getFirst() Returns the first element in this list.
E getLast() Returns the last element in this list.
Iterator descendingIterator() Returns an iterator over the elements in this reverse.
int indexOf(Object o) Returns element index or else -1
ListIterator listIterator(int index) Create iterator from specified index.
E remove(int index) Removes the element at the specified position in this list.
E removeFirst() Removes and returns the first element from this list.
E removeLast() Removes and returns the last element from this list.
E set(int index, E element) Replace index element with specified element.
int size() Returns the number of elements in this list.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 45
Practice @ www.onlinejavacompiler.com

Set Interface

Set:
 Set doesn’t allow duplicates.
 Set is not index based.
HashSet Methods are:
boolean add(E e) Adds the specified element to this set if it is not already present.
void clear() Removes all of the elements from this set.
Object clone() Returns a shallow copy: the elements themselves are not cloned.
boolean contains(Object o) Returns true if this set contains the specified element.
boolean isEmpty() Returns true if this set contains no elements.
Iterator<E> iterator() Returns an iterator over the elements in this set.
boolean remove(Object o) Removes the specified element from this set if it is present.
int size() Returns the number of elements in this set (its cardinality).

Note: Set is not providing any methods to perform index-based operations.


Implementations are:
1. HashSet: It doesn’t maintain insertion order
2. LinkedHashSet: It maintains insertion order of elements.
3. TreeSet: It maintains sorted order of elements.

Program to store elements into HashSet and display:


import java.util.*;
class Code {
public static void main(String[] args) {
Set<Integer> set = new HashSet<Integer>();
set.add(50);
set.add(40);
set.add(30);
set.add(20);
set.add(10);
System.out.println("Set : " + set);
}
}
Output: Random order of elements

Program to store elements into LinkedHashSet and display:


import java.util.*;
class Code {
public static void main(String[] args) {
Set<Integer> set = new LinkedHashSet<Integer>();
set.add(50);
set.add(40);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 46
Practice @ www.onlinejavacompiler.com

set.add(30);
set.add(20);
set.add(10);
System.out.println("Set : " + set);
}
}
Output: 50, 40, 30, 20, 10

Program to store elements into TreeSet and display:


import java.util.*;
class Code {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<Integer>();
set.add(50);
set.add(40);
set.add(30);
set.add(20);
set.add(10);
System.out.println("Set : " + set);
}
}
Output: 10, 20, 30, 40, 50

Remove duplicates in ArrayList:


 ArrayList is ordered and allow duplicates.
 To remove duplicates in array, we simply convert into Set and display
import java.util.*;
class Code {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i=1 ; i<=4 ; i++) {
list.add(i+2);
list.add(i+3);
}
System.out.println("List : " + list);
Set<Integer> set = new HashSet<Integer>(list);
System.out.println("Set : " + set);
}
}

Output: List : [3, 4, 4, 5, 5, 6, 6, 7]


Set : [3, 4, 5, 6, 7]

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 47
Practice @ www.onlinejavacompiler.com

Map Interface

Map:
 Store values using keys
Map = {key=value, key=value, key=value ….}
 Keys must be unique in Map
 Values can be duplicated.
 For example, book names(unique) with prices(duplicates)
o Books = {C=300.0 , C++=300.0, Java=350.0, Python=330.0};

Methods are:
Method Description
put(K key, V value) store value using key.
V get(Object key) return value of specified key.
boolean isEmpty() Returns true if this map contains key-values.
void clear() Removes all elements.
boolean containsKey(Object key) Returns true if map contains specified key.
Set<K> keySet() Returns a Set of keys contained in this map.
remove(Object key) Removes key-value of specified key.
replace(K key, V value) Replace the value of specified key with given value.
int size() Returns the number of key-values in map.
Collection<V> values() Returns Collection of values in this map.

Program to create HashMap and display:


import java.util.*;
class Code
{
public static void main(String[] args)
{
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(10, "Ten");
map.put(20, "Twenty");
map.put(30, "Thirty");
map.put(40, "Fourty");
map.put(50, "Fifty");
System.out.println("Map : " + map);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 48
Practice @ www.onlinejavacompiler.com

Implementations of Map:
1. HashMap: doesn’t maintain insertion order. Allows only one null key
2. LinkedHashMap: maintains insertion order. Allows only one null key
3. TreeMap: maintains sorted order of keys. It doesn’t allow null key.
4. Hashtable: It is call legacy class. It maintains sorted order. It doesn’t allow null key.

import java.util.*;
class Code {
public static void main(String[] args) {
//Map<Integer,String> map = new LinkedHashMap<Integer,String>();
Map<Integer,String> map = new TreeMap<Integer,String>();
map.put(50, "Fifty");
map.put(40, "Fourty");
map.put(30, "Thirty");
map.put(20, "Twenty");
map.put(10, "Ten");
System.out.println("Map : " + map);
}
}

Set<K> keySet():
 We cannot iterate the map object either by using Iterator or using for-each loop.
 First we need to collect all keys of map using keySet() method.
 We iterate keys set and get values by specifying each key.
import java.util.*;
class Code {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(10, "Ten");
map.put(20, "Twenty");
map.put(30, "Thirty");
map.put(40, "Fourty");

System.out.println("Map is : ");
Set<Integer> keys = map.keySet();
for(Integer key : keys){
String value = map.get(key);
System.out.println(key + " = " + value);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 49
Practice @ www.onlinejavacompiler.com

Iterate Map through Iterator:


 Collect the keys using keySet() method.
 Create Iterator from the keys Set.
 Iterate the object and get Values by specifying keys.
import java.util.*;
class Code {
public static void main(String[] args) throws Exception {
String[] books = {"C", "C++", "Java", "Python", "Android"};
double[] prices = {200.0, 300.0, 250.0, 200.0, 250.0};

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


for(int i=0 ; i<=books.length-1 ; i++) {
map.put(books[i], prices[i]);
}

System.out.println("Map is : ");
Set<String> keys = map.keySet();
Iterator<String> itr = keys.iterator();
while(itr.hasNext()) {
String key = itr.next();
Double value = map.get(key);
System.out.println(key + " = " + value);
}
}
}

Menu Driven Program (Books and Prices)


import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String, Double> map = new HashMap<String, Double>();
while(true){
System.out.println("1. Add Book");
System.out.println("2. Update Book");
System.out.println("3. Display Book");
System.out.println("4. Remove Book");
System.out.println("5. Quit");

System.out.print("Enter your choice : ");


int ch = sc.nextInt();

if(ch==1) {

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 50
Practice @ www.onlinejavacompiler.com

System.out.print("Enter Book Name : ");


String name = sc.next();
if(map.containsKey(name)) {
System.out.println("Book already exists");
}
else {
System.out.print("Enter Price : ");
double price = sc.nextDouble();
map.put(name, price);
System.out.println("Book added");
}
}
else if(ch==2) {
System.out.print("Enter Book Name : ");
String name = sc.next();
if(map.containsKey(name)) {
System.out.print("Enter Price : ");
double price = sc.nextDouble();
map.replace(name, price);
System.out.println("Book updated");
}
else
System.out.println("Error : Invalid Book Name");
}
else if(ch==3){
System.out.print("Enter Book Name : ");
String name = sc.next();
if(map.containsKey(name)){
System.out.println("Price : " + map.get(name));
}
else
System.out.println("Error : Invalid Book Name");
}
else if(ch==4){
System.out.print("Enter Book Name : ");
String name = sc.next();
if(map.containsKey(name)){
map.remove(name);
System.out.println("Book removed");
}
else
System.out.println("Error : Invalid Book Name");
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 51
Practice @ www.onlinejavacompiler.com

else if(ch==5){
System.out.println("End");
System.exit(1);
}
else
System.out.println("Invalid choice");
}
}
}

Account Details – Menu Driven Program


Account.java:
public class Account{
private int number;
private String name;
private double balance;
private String location;
public void setNumber(int number){
this.number = number;
}
public void setName(String name){
this.name = name;
}
public void setBalance(double balance){
this.balance = balance;
}
public void setLocation(String location){
this.location = location;
}
public int getNumber(){
return this.number;
}
public String getName(){
return this.name;
}
public double getBalance(){
return this.balance;
}
public String getLocation(){
return this.location;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 52
Practice @ www.onlinejavacompiler.com

Main.java:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<Integer, Account> map = new HashMap<Integer, Account>();
while(true){
System.out.println("1. Add Account");
System.out.println("2. Update Location");
System.out.println("3. Display Account");
System.out.println("4. Remove Account");
System.out.println("5. Quit");

System.out.print("Enter your choice : ");


int ch = sc.nextInt();

if(ch==1){
System.out.print("Enter Account Number : ");
Integer number = sc.nextInt();
if(map.containsKey(number)){
System.out.println("Account already exists");
}
else{
System.out.print("Enter Name :");
String name = sc.next();
System.out.print("Enter Balance :");
double balance = sc.nextDouble();
System.out.print("Enter Location :");
String location = sc.next();

Account acc = new Account();


acc.setNumber(number);
acc.setName(name);
acc.setBalance(balance);
acc.setLocation(location);

map.put(number, acc);
System.out.println("Account added");
}
}
else if(ch==2){
System.out.print("Enter Account Number : ");
int number = sc.nextInt();

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 53
Practice @ www.onlinejavacompiler.com

if(map.containsKey(number)){
System.out.print("Enter location : ");
String location = sc.next();
Account acc = map.get(number);
acc.setLocation(location);
System.out.println("Location updated");
}
else
System.out.println("Error : Invalid acc-number");
}
else if(ch==3){
System.out.print("Enter Account Number : ");
int number = sc.nextInt();
if(map.containsKey(number)){
Account acc = map.get(number);
System.out.println("Details : " + acc.getName() + ", " +
acc.getBalance() + ", " + acc.getLocation());
}
else
System.out.println("Error : Invalid Account");
}
else if(ch==4){
System.out.print("Enter Account Number : ");
int number = sc.nextInt();
if(map.containsKey(number)){
map.remove(number);
System.out.println("Account removed");
}
else
System.out.println("Error : Invalid Account");
}
else if(ch==5){
System.out.println("End");
System.exit(1);
}
else
System.out.println("Invalid choice");
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 54
Practice @ www.onlinejavacompiler.com

Comparator interface
Comparator:
 Comparator is used to order the objects of a user-defined class.
 Comparator provides multiple sorting sequences hence we can sort the elements based
on different data members, for example, rollno, name, age or anything else.

Method Description
public int compare(Object o1, Object o2) Compares first and second object in the list.
public boolean equals(Object obj) Compares this object with specified object.

Compare Student objects based on Age:


Student.java:
class Student {
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}

AgeComparator.java: We need to implement the Comparator interface and override the


compare method to compare 2 objects and then decide to sort.

class AgeComparator implements Comparator {


public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age>s2.age)
return 1;
else
return -1;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 55
Practice @ www.onlinejavacompiler.com

Main.java:
import java.util.*;
import java.io.*;
class Main
{
public static void main(String args[]){
ArrayList<Student> list=new ArrayList<Student>();
list.add(new Student(101,"Vijay",23));
list.add(new Student(106,"Ajay",27));
list.add(new Student(105,"Jai",21));
list.add(new Student(103, "Amar", 13));
System.out.println("Sort by age");
Collections.sort(list,new AgeComparator());
System.out.println("After Sort : ");
for(Student st : list){
System.out.println(st.rollno+" , "+st.name+" , "+st.age);
}
}
}
}

Compare Student objects based on Name:


NameComparator.java:
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}

Sort based on Employee salary:


MySalaryComp.java:
class MySalaryComp implements Comparator<Empl>{
@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary())
return 1;
else
return -1;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 56
Practice @ www.onlinejavacompiler.com

Java 8 Comparator interface


 Java 8 Comparator interface is a functional interface that contains only one abstract
method.
 It is providing many static and default methods to compare different types of object
elements.
 Now, we can use the Comparator interface as the assignment target for a lambda
expression or method reference.

Sorting objects information using Student Age and Name:


Student.java:
class Student
{
private int rollno;
private String name;
private int age;
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Main.java:
import java.util.*;
public class Code
{
public static void main(String args[])
{
ArrayList<Student> al=new ArrayList<Student>();
int nums[] = {101, 102, 103, 104};

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 57
Practice @ www.onlinejavacompiler.com

String names[] = {"Amar", "Swathi", "Sathya", "Harin"};


int ages[] = {23, 30, 17, 25};

for(int i=0 ; i<nums.length ; i++)


{
Student obj = new Student();
obj.setRollno(nums[i]);
obj.setName(names[i]);
obj.setAge(ages[i]);
al.add(obj);
}

Comparator<Student> cm1=Comparator.comparing(Student::getName);
Collections.sort(al,cm1);
System.out.println("Sorting by Name");
for(Student st: al)
{
System.out.println(st.getRollno()+" , "+st.getName()+" , "+st.getAge());
}

Comparator<Student> cm2=Comparator.comparing(Student::getAge);
Collections.sort(al,cm2);
System.out.println("Sorting by Age");
for(Student st: al)
{
System.out.println(st.getRollno()+" , "+st.getName()+" , "+st.getAge());
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 58
Practice @ www.onlinejavacompiler.com

Java-8 Features

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 59
Practice @ www.onlinejavacompiler.com

JDK 8 Features in Java

Features are:
 Static Methods in Interface (JDK7)
 Default Methods in interface
 Functional Interface
 Lambda expression
 Method references
 forEach() method
 Stream API
 Parallel Streams
 Predicates

Purpose of JDK-8:
 Using java technology, application development became easy.
 Billions of applications developed under java. Day by day the data increasing rapidly with
the use of these applications and data processing become complex.
 JDK8 features are the solution to implement data processing techniques easily.
 Data processing important – for quick results

In Java, how we store information?


 Java stores information in the form of objects.
 We store group of Objects in Collections.
 Java 8 features mainly used to process the information of Collections.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 60
Practice @ www.onlinejavacompiler.com

Static and Default Methods in Interface

Interface (before JDK7):


 Interface is a collection of abstract methods.
 Interface methods are by default public and abstract.
 Any class can implement interface
 Implemented class override abstract methods.

Note: The object address of implemented class assign to Interface type reference variable.
InterfaceName obj = new ImplementedClass();

interface Test
{
void m1(); // public abstract
}
class Demo implements Test {
public void m1() {
System.out.println("m1...");
}
}
class Main {
public static void main(String[] args) {
Test obj = new Demo(); // upcasting
obj.m1();
}
}

 Interface variables are by default public static final.


 We must initialize variables defined in interface.
 We cannot modify the variables as they are final.

interface Code
{
int a = 10; // public static final
}
class Main {
public static void main(String[] args) {
System.out.println("a value : " + Code.a);
Code.a = 20 ; // Error : final variable cannot be modified
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 61
Practice @ www.onlinejavacompiler.com

Static and Default Methods

Interface (since jdk7):


 Interface allowed to define static methods from jdk7
 Static methods can access using identity of interface.

Note: Static methods are used to define the common functionality of objects which are
implemented from that interface.

interface CreditCard {
String cartType = "VISA-Platinum";
static void benefits(){
System.out.println("Benefits on Flying, Dining and more");
}
}

Default Methods:
 Defining a method with default keyword.
 We can access Default methods through object reference.

Note: Default methods allow the interfaces to have methods with implementation without
affecting the classes that implement the interface.

interface Vehicle{
default String airBags(){
return "Two airbags";
}
default String alarmOn(){
return "at speed of 100";
}
int maxSpeed();
}
class Alto implements Vehicle{
public int maxSpeed(){
return 160;
}
}
class Swift implements Vehicle{
public int maxSpeed(){
return 220;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 62
Practice @ www.onlinejavacompiler.com

Functional Interface in Java

Functional Interface:
 Interface that accepts only one abstract method.
 We must define with annotation @FunctionalInterface.
 Functional Interface allow static and default methods.

@FunctionalInterface
interface Test
{
void m1();
void m2(); // Error :
}

Static Methods and Default Methods in Functional Interface:


@FunctionalInterface
interface First
{
static void m1(){
System.out.println("Static method");
}
default void m2(){
System.out.println("Default method");
}
void m3();
}
class Second implements First
{
public void m3(){
System.out.println("Instance method");
}
}
class Main
{
public static void main(String[] args)
{
First obj = new Second();
First.m1();
obj.m2();
obj.m3();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 63
Practice @ www.onlinejavacompiler.com

Lambda Expressions

Lambda Expression: Lambda expression is a simplest form of Functional interface


implementation.

In how many ways we can implement a Functional Interface:


1. Through class
2. Through anonymous inner class
3. Through lambda expression

1. Implement interface using class:


@FunctionalInterface
interface First {
void fun();
}
class Second implements First {
public void fun(){
System.out.println("fun...");
}
}
class Main {
public static void main(String[] args) {
First obj = new Second();
obj.fun();
}
}

2. Through Anonymous inner class: Defining a class without identity is called Anonymous
inner class. We always define anonymous class inside a method.
interface Test {
void fun();
}
class Main {
public static void main(String[] args) {
Test obj = new Test() {
public void fun() {
System.out.println("Anonymous fun");
}
};
obj.fun();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 64
Practice @ www.onlinejavacompiler.com

Through Lambda expression:


 Expression is a line of code.
 Lambda expression is the implementation of Functional Interface in a short format
@FunctionalInterface
interface Test
{
void fun();
}
class Main
{
public static void main(String[] args) {
Test obj = () -> System.out.println("Lambda fun");
obj.fun();
}
}

If the method not taking any parameter:


() -> expression

If the method taking only one parameter:


parameter -> expression

If the method taking more than one parameter:


(parameter1, parameter2) -> expression

Lambda expression as block:


 Expressions immediately return a value, and they cannot contain variables, assignments
or statements such as if or for.
 In order to do more complex operations, a code block can be used with curly braces.
 If the lambda expression needs to return a value, then the code block should have a
return statement.
(parameter1, parameter2) -> {
stat-1;
stat-2;
stat-3;
return
}

Lamba expression with arguments:


 Lambda expression can take arguments based on the signature of method defined in
functional interface.
 No need to specify the data types while representing the arguments in lambda
expression.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 65
Practice @ www.onlinejavacompiler.com

@FunctionalInterface
interface Calc
{
void add(int x, int y);
}
class Main
{
public static void main(String[] args)
{
Calc obj = (x, y) -> System.out.println("Sum : " + (x+y));
obj.add(5,3);
obj.add(10,20);
}
}

Lambda expression with return values: Lambda expression automatically returns the value
which is evaluated in expression. We need to specify the return type in Functional Interface
specification.
@FunctionalInterface
interface Calc
{
int add(int x, int y);
}
class Main
{
public static void main(String[] args)
{
Calc obj = (x, y) -> x+y;

System.out.println("Sum : " + obj.add(5,3));


System.out.println("Sum : " + obj.add(10,20));
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 66
Practice @ www.onlinejavacompiler.com

Method References in Java

Method references:
 It is JDK8 feature.
 It is used to refer any method of functional interface easily.
 Any method definition can be assigned to functional interface method identity and
access the using its identity.

Method reference to static method as follows:


@FunctionalInterface
interface Test {
void abc();
}
class Demo {
static void fun() {
System.out.println("fun...");
}
}
class Main {
public static void main(String[] args) {
Test obj = Demo::fun;
obj.abc();
}
}

Method reference to an instance method:


@FunctionalInterface
interface Test {
void abc();
}
class Demo {
void fun() {
System.out.println("fun...");
}
}
class Main {
public static void main(String[] args) {
Test obj = new Demo()::fun;
obj.abc();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 67
Practice @ www.onlinejavacompiler.com

forEach() method:
 forEach() introduced in JDK8 to iterate the collection easily.
 forEach() defined in both Iterable interface and in Stream interface.
 forEach() method is a Default method.
default void forEach(Consumer<super T>action)

Note: forEach() method takes a single parameter which is a functional interface. So, you can
pass lambda expression or method reference as input.

Iterating List
Defining a List:
List<String> names = Arrays.asList("C", "Java", "Python");

using lambda expression:


names.forEach(name->System.out.println(name));

using method reference:


names.forEach(System.out::println);

Iterating Set
Defining a Set:
Set<String> uniqueNames = new HashSet<>(Arrays.asList("C", "C++", "Java"));

using lambda expression:


uniqueNames.forEach(name->System.out.println(name));

using method reference:


uniqueNames.forEach(System.out::println);

Iterating Map
Defining a Map:
Map<Integer, String> namesMap = new HashMap<>();
namesMap.put(1, "Java");
namesMap.put(2, "JDBC");
namesMap.put(3, "JSP");

Iterate map:
namesMap.forEach((key, value) -> System.out.println(key + " " + value));

Iterating Map using entrySet:


namesMap.entrySet().forEach(entry -> System.out.println(
entry.getKey() + " " + entry.getValue()));

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 68
Practice @ www.onlinejavacompiler.com

Iterate List:
import java.util.*;
import java.util.*;
class Main
{
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50));
list.forEach(x->System.out.println(x));
}
}

Iterate Set:
import java.util.*;
import java.util.*;
class Main
{
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50));
Set<Integer> set = new HashSet<>(list);
set.forEach(x->System.out.println(x));
}
}

Iterate Map:
import java.util.*;
import java.util.*;
class Main
{
public static void main(String[] args)
{
Map<Integer,String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Servlets");
map.put(3, "JSP");
map.forEach((k, v)->System.out.println(k + " = " + v));
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 69
Practice @ www.onlinejavacompiler.com

Stream API
Stream API:
 Stream is a flow of data.
 Stream API providing pre-defined functionality by which we can filter the data easily.
 We always create Streams to Collection objects and filter the data stored in collections.

Note: Stream is a not a data structure hence it will not hold any information. Stream will not
change the collection object. It just processes the elements of object by without modifying it.

Creating Stream to List: stream() method returns the stream of any collection object
Stream<Integer> st = list.stream();

forEach() method in Stream interface:


 Stream API related interfaces and classes belongs to java.util.stream package.
 forEach() method belongs to Stream class also.
 We invoke the forEach() method on Stream object to display the data.

Display Stream information using forEach() and Lambda:


import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50));
Stream<Integer> st = list.stream();
st.forEach(x->System.out.println(x));
}
}

Stream and display the list in single line:


import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50));
list.stream().forEach(x->System.out.println(x));
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 70
Practice @ www.onlinejavacompiler.com

map() and filter() methods of Stream

map():
 It takes a lambda expression as its only argument, and uses it to change every individual
element in the stream.
 Its return value is a new Stream object containing the changed elements.

Creating a Stream:
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(5);
myList.add(8);
Stream<Integer> myStream = myList.stream();

We can create streams for arrays as follows:


Integer[] myArray = {1, 5, 8};
Stream<Integer> myStream = Arrays.stream(myArray);

map to convert all elements in an array of strings to uppercase:


String[] myArray = new String[]{"harin", "satya", "annie", "amar"};
Stream<String> myStream = Arrays.stream(myArray);
Stream<String> myNewStream = myStream.map(s -> s.toUpperCase());

To convert it into an array, you use its toArray method:


String[] myNewArray = myNewStream.toArray(String[]::new);

filter():
 filter() method takes lambda expression as input and return boolean value.
 If filter() method returns true, then the element enter into resultant stream.
 filter() method returns stream after filtering the data.

Program to filter the Strings starts with “s” in a list:


import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Java");
list.add("JDBC");
list.add("Servlets");
list.add("JSP");
list.add("Spring");
list.add("Hibernate");

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 71
Practice @ www.onlinejavacompiler.com

Stream<String> st = list.stream();
Stream<String> res = st.filter(s->s.startsWith("S"));
res.forEach(System.out::println);
}
}

Write the above filtering logic in single line:


list.stream().filter(s->s.startsWith("S")).forEach(System.out::println);

Display string whose length is 4:


import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args)
{
String[] arr = {"Java", "JDBC", "Servlets", "JSP", "Spring"};
List<String> list = new ArrayList<String>();
for(int i=0 ; i<arr.length ; i++)
list.add(arr[i]);

list.stream().filter(s->s.length()==4).forEach(System.out::println);
}
}

Program to display only even numbers in the list using stream api:
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 9, 3, 7, 1, 4, 6};
List<Integer> list = new ArrayList<Integer>();
for(int x : arr){
list.add(x);
}
System.out.println("List is : " + list);
System.out.println("Even numbers list is : ");
list.stream().filter(s->s%2==0).forEach(System.out::println);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 72
Practice @ www.onlinejavacompiler.com

Collectors Class
Collectors: Collectors is a final class. It provides methods to collect filtered elements into various
collections, and performing operations on collected data such as counting elements, reverse,
sort etc.

Store into List:


List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers.stream().map(x -> x*x).collect(Collectors.toList());

output: [1,4,9,16,25,36,36]

Store into Set:


List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers.stream().map(x -> x*x).collect(Collectors.toSet());

output: [1,4,9,16,25,36]

Store into Specific Collection:


List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers
.stream()
.filter(x -> x >2)
.collect(Collectors.toCollection(LinkedList::new));

output: [3,4,5,6,6]

Counting elements:
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
Long collect = integers
.stream()
.filter(x -> x <4)
.collect(Collectors.counting());

Output: 3

Finding minimum value: minBy()


List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers
.stream()
.collect(Collectors.minBy(Comparator.naturalOrder()))
.get();

Output: 1

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 73
Practice @ www.onlinejavacompiler.com

Collections – Interview Questions

1. Define Variable and Method?


 Variable: Is used to Store the data
double balance ;

 Method: Is used to Process the data


getBalance();
setBalance();

2. Define Array?
 Array: Is a set of similar data elements
long[] accNums;

3. Define Object?
 Object is a set of dis-similar data elements. For example, Student details,
Employee details, Customer details etc.

4. Define Collection?
 Collection is set of Objects. Set of Student details, Employee details.

5. Collection Interface and Classes:

6. Array v/s ArrayList


 Array is Static (Fixed size)
 ArrayList is Dynamic (No Fixed Size)

7. Define List:
 List is ordered
 List allow duplicates
 List is index based
8. Define Set:

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 74
Practice @ www.onlinejavacompiler.com

 Set is not ordered


 Set doesn’t allow duplicates
 Set is not index based

9. Define Map:
 Map store elements using keys
 Keys must be unique
 Values can be duplicated.

10. ArrayList v/s Vector:


 Vector is synchronized by default
 ArrayList is not synchronized by default

11. Vector v/s Stack:


 Vector is index based
 Stack follows LIFO (Last In First Out)

12. ArrayList v/s LinkedList:


 In ArrayList: Accessing elements is faster (index based)
Occupies Less memory.
Insertions and Deletions are Slower
 In LinkedList: Insertions and Deletions are faster (no shifting of elements)
Occupies More memory.

13. Define HashSet, LinkedHashSet and TreeSet?


 HashSet: doesn’t maintains insertion order of elements
 LinkedHashSet: maintains insertion order of elements
 TreeSet: maintains sorted order of elements

14. Define HashMap, LinkedHashMap and TreeMap?


 HashMap: doesn’t maintain insertion order of elements
 LinkedHashMap: maintains insertion order of elements
 TreeMap: maintains sorted order of elements using keys.

15. Define Hashtable?


 Hashtable store elements using keys.
 Hashtable doesn’t allow null keys.

16. Explain null values in collections?


 List is allowed to store any number of null values
 Set is allowed to store only one null value
 In map – we can store one null key but any number of null values
17. Which of the Collections synchronized by default?

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 75
Practice @ www.onlinejavacompiler.com

 Only legacy collection classes synchronized by default


Examples: Vector, Stack and Hashtable

18. Define PriorityQueue?


 Store elements in insertion order but display elements using their priority

19. Differentiate Iterator and ListIterator?


 Iterator: Process elements one by one in forward direction
Iterator is not index based
Iterator can process List, Set and Map
 ListIterator: Process elements using specified index
Iterator can process only List(Set and Map not index based)

20. Define Boxing and Unboxing?


 Boxing: Conversion of primitive data to Object
 Unboxing: Conversion of Object type data to primitive

21. Define Auto-Boxing and Auto Unboxing?


 Auto-Boxing: Auto conversion from primitive to Object
 Auto Unboxing: Auto conversion from object to primitive
Note: Auto Boxing & Auto Unboxing since jdk5

22. Define Comparable and Comparator?


 Comparable and Comparator is used sort record type objects.
 Comparable sort objects based on single value like id or name or location
 Comparator sort objects based on multiple values like id-name, name-location,
id-location.

23. Define Collections class?


 Collections is a class belongs to util package
 Collections class providing searching, sorting and conversion methods to process
collection objects easily.

24. Collection v/s Collection with Generics:


 Collection: Collection accepts any type of object.
No type safety.
 Collection with Generics: Collection with Generics allow to store specified type
of Objects. Generics for type safety.

25. How to convert ArrayList to Array?


 Arrays.asList(item);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 76
Practice @ www.onlinejavacompiler.com

JDK8 Features – Interview Questions

1. What are JDK8 features?


 Functional Interface
 Static and Default methods in interface
 Lambda expressions
 Method references
 forEach() method
 Stream API
 Collectors class
 Predicates

2. What is the use of JDK8 features?


 With JDK8 – Data processing become easy.
 JDK8 features are used to process the information quickly and with short code.
 Streaming the data is used to perform operations like searching, sorting, filtering,
parallel processing etc.

3. What is an interface in JDK8?


 Since JDK8, interface allow static and default methods along with abstract
methods final variables.

4. Explain static methods in interface?


 Defining a method with static keyword. Static represents common functionality of
interface. Static methods can access using identity of interface.

5. How to define default methods?


 Define a method using default keyword. We can access default methods using
object reference.

6. What is Functional Interface?


 An interface with only one abstract method.
 It is recommended to define Functional Interface using @FunctionalInterface
annotation.
 It allows any number of static and default methods.

7. What is anonymous inner class?


 Define a class without identity inside the method. We often implement interfaces
as anonymous inner classes.

8. What is lambda expression?


 Easy implementation of functional interface.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 77
Practice @ www.onlinejavacompiler.com

 Lambda expression is an object and address are assigned to FunctionalInterface


reference variable.

9. What are the methods of Iterable interface?


 public Iterator iterator()
 public default void forEach()
 public default SplitIterator splitIterator()

10. Define Method references?


 Method references are used to refer static or instance method of a class.
 It is mainly used to refer a method of Functional interface.

11. How to create reference to static method?


 ClassName::MethodName

12. How to create reference to instance method?


 new ClassName()::MethodName

13. Define forEach() method?


 It is used to iterate element of collection or stream
 It is belonging to Iterable interface & Stream interface

14. How can we display the elements of List in jdk8?


 Lambda expression:
 list.forEach(n->System.out.println(n));
 Method reference:
 list.forEach(System.out::println);

15. What is Stream API?


 Stream is a flow of data.
 We can create streams to collection object data to process elements.
 Stream enables us to combine multiple operations on data to get desired result.
 Jjva.util.stream package is providing Stream interface

16. How to create Stream for List?


 Stream<E> s = list.stream();

17. How to sort list elements using stream api?


 list.stream().sorted().forEach(System.out::println);

18. Define Collectors class?


 Collectors class belongs to java.util. package.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 78
Practice @ www.onlinejavacompiler.com

 Collectors class providing functionality to collect the processed data into List, Set
or Map through streaming.

19. How to collect sorted elements into list using stream api?
 list.stream().sorted().collect(Collectors.toList());

20. Collect the sorted elements into List through streaming and display list?
 list.stream().sorted().collect(Collectors.toList()).forEach(System.out::println);

21. What is Parallel streaming?


 By default, every stream in java is sequential unless we specify the parallel stream
explicitly as follows
 Stream st = collection.stream().paralle();

22. Differentiate forEach() and forEachOrdered()?


 forEach() method is not guarantee about order of elements in parallel streaming
 forEachOrdered() method is guarantee about elements order.

23. How to display the elements greater than 5 in a List using filter() method?
 list.stream().filter(n->n>5).forEach(System.out::println);

24. How to collect the elements greater than 5 in List using filter() method?
 List<Integer> res = list.stream().filter(n->n>5).collect(Collectors.toList());

25. What is Optional Class?


 Optional class is used to handle NullPointerException

26. What is Java Predicate?


 It is a functional interface belongs to java.util.function package.
 It predicates the input argument and returns a Boolean value.

@FunctionalInterface
interface Predicate
{
public boolean test(E e);
}

27. How can we create Predicate that display only integers greater than 5?
 Predicate<E> pr = n -> n>5;

28. How to filter list elements which are greater than 5 using predicate?
 Predicate<Integer> pr = n -> n>5;
 list.stream().filter(pr).forEach(System.out::println);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 79
Practice @ www.onlinejavacompiler.com

29. How to filter list of strings starts with ‘A’ using predicate and parallel stream and please
guarantee about the order of elements?
 Predicate<String> pr = s->s.startsWith(“A”);
 List.stream().parallel().filter(pr).forEachOrdered(System.out::println);

30. How can we pass a method reference to predicate?


 Predicate<E> pr = ClassName::methodName;
 Or
 Predicate<E> pr = new ClassName::methodName;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 80

You might also like