SlideShare a Scribd company logo
Collection Framework
Handled By
Dr.T.Abirami
Associate Professor
Department of IT
Kongu Engineering College Perundurai
What is a Framework?
• A framework is a set
of classes and interfaces which provide a ready-
made architecture.
• An optimal object-oriented design always
includes a framework with a collection of classes
such that all the classes perform the same kind
of task.
Collections in Java / Collections
Framework
• The Java collections framework provides a set
of interfaces and classes to implement various
data structures and algorithms.
• Java Collections can achieve all the operations
that you perform on a data such as searching,
sorting, insertion, manipulation, and
deletion.
What is Collection in Java
• Java Collection means a single unit of objects.
(i.e., a group)
• Java Collection framework provides many
interfaces
(Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
Hierarchy of Collection Framework
Java  Collections
Methods of Collection interface
No. Method Description
1 public boolean add(E e) It is used to insert an element in this collection.
2 public boolean addAll(Collection<?
extends E> c)
It is used to insert the specified collection elements in the invoking collection.
3 public boolean remove(Object element) It is used to delete an element from the collection.
4 public boolean
removeAll(Collection<?> c)
It is used to delete all the elements of the specified collection from the invoking
collection.
5 default boolean removeIf(Predicate<?
super E> filter)
It is used to delete all the elements of the collection that satisfy the specified
predicate.
6 public boolean retainAll(Collection<?>
c)
It is used to delete all the elements of invoking collection except the specified
collection.
7 public int size() It returns the total number of elements in the collection.
8 public void clear() It removes the total number of elements from the collection.
9 public boolean contains(Object
element)
It is used to search an element.
10 public boolean
containsAll(Collection<?> c)
It is used to search the specified collection in the collection.
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts collection into array.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of the returned array is
that of the specified array.
14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as its source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of the collection.
List Interface
• To store the ordered collection of objects. It
can have duplicate values.
• List interface is implemented by the classes
ArrayList, LinkedList, Vector, and Stack.
Example
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
The classes that implement the List
interface are given below.
ArrayList :
• The ArrayList class implements the List
interface.
• It uses a dynamic array to store the duplicate
element of different data types.
• The ArrayList class maintains the insertion
order and is non-synchronized.
• The elements stored in the ArrayList class can
be randomly accessed.
Java  Collections
Java Iterators
• to access every item in a collection of items - We
call this traversing or iterating
• Example: array for
(inti = 0; i < array.length; i++)
// do something with array[i]
• Java provides an interface for stepping through all
elements in any collection, called an iterator
Iterating through an ArrayList
• Iterating through an ArrayListn Iterating through an
ArrayList of Strings:
for (int i = 0; i < list.size(); i++)
{
String s = list.get(i); //do something with s
}
Alternative:
Iterator<String> itr = list.iterator();
while (itr.hasNext())
{
String s = list.next();
}
This syntax of iteration is generic and
applies to any Java class that implements
the Iterator interface
the code will work even if we decide to store
the data in a different data structure (as long
as it provides an iterator)
Iterator Interface
Iterator<T>: - a generic interface with the following
methods
• public booleanhasNext(); returns true if there are
more elements to iterate over
• public T next(); returns the next element
– throws a NoSuchElement exception if a next element
does not exist
• public void remove(); removes the last element
returned by the iterator (optional operation)
• It is in the java.utilpackage
ArrayList :
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
• LinkedList implements the Collection interface.
• It uses a doubly linked list internally to store the
elements.
• It can store the duplicate elements. It
maintains the insertion order and is not
synchronized.
• In LinkedList, the manipulation is fast because
no shifting is required.
Java  Collections
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
LinkedList
Output:
Ravi
Vijay
Ravi
Ajay
Vector
• Vector uses a dynamic array to store the data
elements.
• It is similar to ArrayList.
• However, It is synchronized and contains many
methods that are not the part of Collection
framework.
Java  Collections
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Vector
Stack
• The stack is the subclass of Vector.
• It implements the last-in-first-out data
structure, i.e., Stack.
• The stack contains all of the methods of
Vector class and also provides its methods like
boolean push(),
boolean peek(),
boolean push(object o), which defines its
properties.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Stack
HashSet
• to create a collection that uses a hash table for
storage.
• It inherits the AbstractSet class and implements Set
interface.
• It stores the elements by using a mechanism
called hashing.
• It contains unique elements only.
• It allows null value.
• HashSet class is non synchronized.
• It doesn't maintain the insertion order. Here, elements
are inserted on the basis of their hashcode.
• It is the best approach for search operations.
Difference between List and Set
• A list can contain duplicate elements whereas
Set contains unique elements only.
HashSet example ignoring duplicate
elements
import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ajay
Vijay
Ravi
Java Collections – Map
• A Map is an object that maps keys to values.
• A map cannot contain duplicate keys.
• There are three main implementations of Map
interfaces: HashMap, TreeMap, and
LinkedHashMap.
• HashMap: it makes no guarantees concerning the
order of iteration
• TreeMap: It stores its elements in a red-black tree,
orders its elements based on their values; it is
substantially slower than HashMap.
• LinkedHashMap: It orders its elements based on the
order in which they were inserted into the set
(insertion-order).
HashMap
• HashMap is a Map based collection class that
is used for storing Key & value pairs,
• it is denoted as HashMap<Key, Value> or
HashMap<K, V>.
• This class makes no guarantees as to the order
of the map.
• It is similar to the Hashtable class except that
it is unsynchronized and permits nulls(null
values and null key).
HashMap
• It is not an ordered collection
• which means it does not return the keys and
values in the same order in which they have
been inserted into the HashMap.
• It does not sort the stored keys and Values.
• to import java.util.HashMap or its super class
in order to use the HashMap class and
methods.
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,St
ring>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an array list to store Integer data
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(4);
list1.add(5);
System.out.println("ArrayList of Integer: " + list1);
// creates an array list to store String data
ArrayList<String> list2 = new ArrayList<>();
list2.add("Four");
list2.add("Five");
System.out.println("ArrayList of String: " + list2);
// creates an array list to store Double data
ArrayList<Double> list3 = new ArrayList<>();
list3.add(4.5);
list3.add(6.5);
System.out.println("ArrayList of Double: " + list3);
}
}
Output
ArrayList of Integer:
[4, 5]
ArrayList of String:
[Four, Five]
ArrayList of Double:
[4.5, 6.5]
• we have used the same ArrayList class to store
elements of Integer, String, and Double types.
This is possible because of Java Generics.
• Here, notice the line,
• ArrayList<Integer> list1 = new ArrayList<>();
We have used Integer inside the angle
brackets, <>. The angle bracket, <> is known as
the type parameter in generics.
• The type parameter is used to specify the type
of objects (data) that the generics class or
method works on.
Ad

More Related Content

What's hot (20)

JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Python set
Python setPython set
Python set
Mohammed Sikander
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
HrithikShinde
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
Java packages
Java packagesJava packages
Java packages
BHUVIJAYAVELU
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 

Similar to Java Collections (20)

collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answeredU-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
eyemitra1
 
java unit 4 pdf - about java collections
java unit 4 pdf - about java collectionsjava unit 4 pdf - about java collections
java unit 4 pdf - about java collections
aapalaks
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
bhawna sharma
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
Java util
Java utilJava util
Java util
Srikrishna k
 
Collections Training
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
module2a it is module 2 so it is module 2.pptx
module2a it is module 2 so it is module 2.pptxmodule2a it is module 2 so it is module 2.pptx
module2a it is module 2 so it is module 2.pptx
bharath555tth
 
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylistarraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
Collection Framework.power point presentation.......
Collection Framework.power point presentation.......Collection Framework.power point presentation.......
Collection Framework.power point presentation.......
Betty333100
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdfJava R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
veerendranath12
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answeredU-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
eyemitra1
 
java unit 4 pdf - about java collections
java unit 4 pdf - about java collectionsjava unit 4 pdf - about java collections
java unit 4 pdf - about java collections
aapalaks
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
bhawna sharma
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
module2a it is module 2 so it is module 2.pptx
module2a it is module 2 so it is module 2.pptxmodule2a it is module 2 so it is module 2.pptx
module2a it is module 2 so it is module 2.pptx
bharath555tth
 
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylistarraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
Collection Framework.power point presentation.......
Collection Framework.power point presentation.......Collection Framework.power point presentation.......
Collection Framework.power point presentation.......
Betty333100
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdfJava R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Ad

More from Kongu Engineering College, Perundurai, Erode (20)

Introduction to Generative AI refers to a subset of artificial intelligence
Introduction to Generative AI refers to a subset of artificial intelligenceIntroduction to Generative AI refers to a subset of artificial intelligence
Introduction to Generative AI refers to a subset of artificial intelligence
Kongu Engineering College, Perundurai, Erode
 
Introduction to Microsoft Power BI is a business analytics service
Introduction to Microsoft Power BI is a business analytics serviceIntroduction to Microsoft Power BI is a business analytics service
Introduction to Microsoft Power BI is a business analytics service
Kongu Engineering College, Perundurai, Erode
 
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Kongu Engineering College, Perundurai, Erode
 
concept of server-side JavaScript / JS Framework: NODEJS
concept of server-side JavaScript / JS Framework: NODEJSconcept of server-side JavaScript / JS Framework: NODEJS
concept of server-side JavaScript / JS Framework: NODEJS
Kongu Engineering College, Perundurai, Erode
 
Node.js web-based Example :Run a local server in order to start using node.js...
Node.js web-based Example :Run a local server in order to start using node.js...Node.js web-based Example :Run a local server in order to start using node.js...
Node.js web-based Example :Run a local server in order to start using node.js...
Kongu Engineering College, Perundurai, Erode
 
Concepts of Satellite Communication and types and its applications
Concepts of Satellite Communication  and types and its applicationsConcepts of Satellite Communication  and types and its applications
Concepts of Satellite Communication and types and its applications
Kongu Engineering College, Perundurai, Erode
 
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLANConcepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Kongu Engineering College, Perundurai, Erode
 
Web Technology Introduction framework.pptx
Web Technology Introduction framework.pptxWeb Technology Introduction framework.pptx
Web Technology Introduction framework.pptx
Kongu Engineering College, Perundurai, Erode
 
Computer Network - Unicast Routing Distance vector Link state vector
Computer Network - Unicast Routing Distance vector Link state vectorComputer Network - Unicast Routing Distance vector Link state vector
Computer Network - Unicast Routing Distance vector Link state vector
Kongu Engineering College, Perundurai, Erode
 
Android SQLite database oriented application development
Android SQLite database oriented application developmentAndroid SQLite database oriented application development
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
Android Application Development Programming
Android Application Development ProgrammingAndroid Application Development Programming
Android Application Development Programming
Kongu Engineering College, Perundurai, Erode
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...
Kongu Engineering College, Perundurai, Erode
 
SOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptxSOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptx
Kongu Engineering College, Perundurai, Erode
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Application Layer.pptx
Kongu Engineering College, Perundurai, Erode
 
Connect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptxConnect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptx
Kongu Engineering College, Perundurai, Erode
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
Kongu Engineering College, Perundurai, Erode
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
Navigation Bar.pptx
Kongu Engineering College, Perundurai, Erode
 
Bootstarp installation.pptx
Bootstarp installation.pptxBootstarp installation.pptx
Bootstarp installation.pptx
Kongu Engineering College, Perundurai, Erode
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
Kongu Engineering College, Perundurai, Erode
 
Ad

Recently uploaded (20)

Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Crack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By VivekCrack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By Vivek
Vivek Srivastava
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis""Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
Infopitaara
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........
jinny kaur
 
Building Security Systems in Architecture.pdf
Building Security Systems in Architecture.pdfBuilding Security Systems in Architecture.pdf
Building Security Systems in Architecture.pdf
rabiaatif2
 
aset and manufacturing optimization and connecting edge
aset and manufacturing optimization and connecting edgeaset and manufacturing optimization and connecting edge
aset and manufacturing optimization and connecting edge
alilamisse
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptxLecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
huzaifabilalshams
 
vlsi digital circuits full power point presentation
vlsi digital circuits full power point presentationvlsi digital circuits full power point presentation
vlsi digital circuits full power point presentation
DrSunitaPatilUgaleKK
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...
Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...
Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...
LiyaShaji4
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
Kamal Acharya
 
Mirada a 12 proyectos desarrollados con BIM.pdf
Mirada a 12 proyectos desarrollados con BIM.pdfMirada a 12 proyectos desarrollados con BIM.pdf
Mirada a 12 proyectos desarrollados con BIM.pdf
topitodosmasdos
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Crack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By VivekCrack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By Vivek
Vivek Srivastava
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis""Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
Infopitaara
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........
jinny kaur
 
Building Security Systems in Architecture.pdf
Building Security Systems in Architecture.pdfBuilding Security Systems in Architecture.pdf
Building Security Systems in Architecture.pdf
rabiaatif2
 
aset and manufacturing optimization and connecting edge
aset and manufacturing optimization and connecting edgeaset and manufacturing optimization and connecting edge
aset and manufacturing optimization and connecting edge
alilamisse
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptxLecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
huzaifabilalshams
 
vlsi digital circuits full power point presentation
vlsi digital circuits full power point presentationvlsi digital circuits full power point presentation
vlsi digital circuits full power point presentation
DrSunitaPatilUgaleKK
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...
Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...
Explainable-Artificial-Intelligence-in-Disaster-Risk-Management (2).pptx_2024...
LiyaShaji4
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
Kamal Acharya
 
Mirada a 12 proyectos desarrollados con BIM.pdf
Mirada a 12 proyectos desarrollados con BIM.pdfMirada a 12 proyectos desarrollados con BIM.pdf
Mirada a 12 proyectos desarrollados con BIM.pdf
topitodosmasdos
 

Java Collections

  • 1. Collection Framework Handled By Dr.T.Abirami Associate Professor Department of IT Kongu Engineering College Perundurai
  • 2. What is a Framework? • A framework is a set of classes and interfaces which provide a ready- made architecture. • An optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task.
  • 3. Collections in Java / Collections Framework • The Java collections framework provides a set of interfaces and classes to implement various data structures and algorithms. • Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
  • 4. What is Collection in Java • Java Collection means a single unit of objects. (i.e., a group) • Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
  • 7. Methods of Collection interface No. Method Description 1 public boolean add(E e) It is used to insert an element in this collection. 2 public boolean addAll(Collection<? extends E> c) It is used to insert the specified collection elements in the invoking collection. 3 public boolean remove(Object element) It is used to delete an element from the collection. 4 public boolean removeAll(Collection<?> c) It is used to delete all the elements of the specified collection from the invoking collection. 5 default boolean removeIf(Predicate<? super E> filter) It is used to delete all the elements of the collection that satisfy the specified predicate. 6 public boolean retainAll(Collection<?> c) It is used to delete all the elements of invoking collection except the specified collection. 7 public int size() It returns the total number of elements in the collection. 8 public void clear() It removes the total number of elements from the collection. 9 public boolean contains(Object element) It is used to search an element. 10 public boolean containsAll(Collection<?> c) It is used to search the specified collection in the collection. 11 public Iterator iterator() It returns an iterator. 12 public Object[] toArray() It converts collection into array. 13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of the returned array is that of the specified array. 14 public boolean isEmpty() It checks if collection is empty. 15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its source. 16 default Stream<E> stream() It returns a sequential Stream with the collection as its source. 17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the collection. 18 public boolean equals(Object element) It matches two collections. 19 public int hashCode() It returns the hash code number of the collection.
  • 8. List Interface • To store the ordered collection of objects. It can have duplicate values. • List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack. Example List <data-type> list1= new ArrayList(); List <data-type> list2 = new LinkedList(); List <data-type> list3 = new Vector(); List <data-type> list4 = new Stack(); There are various methods in List interface that can be used to insert, delete, and access the elements from the list.
  • 9. The classes that implement the List interface are given below. ArrayList : • The ArrayList class implements the List interface. • It uses a dynamic array to store the duplicate element of different data types. • The ArrayList class maintains the insertion order and is non-synchronized. • The elements stored in the ArrayList class can be randomly accessed.
  • 11. Java Iterators • to access every item in a collection of items - We call this traversing or iterating • Example: array for (inti = 0; i < array.length; i++) // do something with array[i] • Java provides an interface for stepping through all elements in any collection, called an iterator
  • 12. Iterating through an ArrayList • Iterating through an ArrayListn Iterating through an ArrayList of Strings: for (int i = 0; i < list.size(); i++) { String s = list.get(i); //do something with s } Alternative: Iterator<String> itr = list.iterator(); while (itr.hasNext()) { String s = list.next(); } This syntax of iteration is generic and applies to any Java class that implements the Iterator interface the code will work even if we decide to store the data in a different data structure (as long as it provides an iterator)
  • 13. Iterator Interface Iterator<T>: - a generic interface with the following methods • public booleanhasNext(); returns true if there are more elements to iterate over • public T next(); returns the next element – throws a NoSuchElement exception if a next element does not exist • public void remove(); removes the last element returned by the iterator (optional operation) • It is in the java.utilpackage
  • 14. ArrayList : import java.util.*; class TestJavaCollection1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Ravi");//Adding object in arraylist list.add("Vijay"); list.add("Ravi"); list.add("Ajay"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ravi Vijay Ravi Ajay
  • 15. LinkedList • LinkedList implements the Collection interface. • It uses a doubly linked list internally to store the elements. • It can store the duplicate elements. It maintains the insertion order and is not synchronized. • In LinkedList, the manipulation is fast because no shifting is required.
  • 17. import java.util.*; public class TestJavaCollection2{ public static void main(String args[]){ LinkedList<String> al=new LinkedList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } LinkedList Output: Ravi Vijay Ravi Ajay
  • 18. Vector • Vector uses a dynamic array to store the data elements. • It is similar to ArrayList. • However, It is synchronized and contains many methods that are not the part of Collection framework.
  • 20. import java.util.*; public class TestJavaCollection3{ public static void main(String args[]){ Vector<String> v=new Vector<String>(); v.add("Ayush"); v.add("Amit"); v.add("Ashish"); v.add("Garima"); Iterator<String> itr=v.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ayush Amit Ashish Garima Vector
  • 21. Stack • The stack is the subclass of Vector. • It implements the last-in-first-out data structure, i.e., Stack. • The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
  • 22. import java.util.*; public class TestJavaCollection4{ public static void main(String args[]){ Stack<String> stack = new Stack<String>(); stack.push("Ayush"); stack.push("Garvit"); stack.push("Amit"); stack.push("Ashish"); stack.push("Garima"); stack.pop(); Iterator<String> itr=stack.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ayush Garvit Amit Ashish Stack
  • 23. HashSet • to create a collection that uses a hash table for storage. • It inherits the AbstractSet class and implements Set interface. • It stores the elements by using a mechanism called hashing. • It contains unique elements only. • It allows null value. • HashSet class is non synchronized. • It doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode. • It is the best approach for search operations.
  • 24. Difference between List and Set • A list can contain duplicate elements whereas Set contains unique elements only.
  • 25. HashSet example ignoring duplicate elements import java.util.*; class HashSet2{ public static void main(String args[]){ //Creating HashSet and adding elements HashSet<String> set=new HashSet<String>(); set.add("Ravi"); set.add("Vijay"); set.add("Ravi"); set.add("Ajay"); //Traversing elements Iterator<String> itr=set.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Ajay Vijay Ravi
  • 26. Java Collections – Map • A Map is an object that maps keys to values. • A map cannot contain duplicate keys. • There are three main implementations of Map interfaces: HashMap, TreeMap, and LinkedHashMap. • HashMap: it makes no guarantees concerning the order of iteration • TreeMap: It stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashMap. • LinkedHashMap: It orders its elements based on the order in which they were inserted into the set (insertion-order).
  • 27. HashMap • HashMap is a Map based collection class that is used for storing Key & value pairs, • it is denoted as HashMap<Key, Value> or HashMap<K, V>. • This class makes no guarantees as to the order of the map. • It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).
  • 28. HashMap • It is not an ordered collection • which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. • It does not sort the stored keys and Values. • to import java.util.HashMap or its super class in order to use the HashMap class and methods.
  • 29. import java.util.*; public class HashMapExample1{ public static void main(String args[]){ HashMap<Integer,String> map=new HashMap<Integer,St ring>();//Creating HashMap map.put(1,"Mango"); //Put elements in Map map.put(2,"Apple"); map.put(3,"Banana"); map.put(4,"Grapes"); System.out.println("Iterating Hashmap..."); for(Map.Entry m : map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }
  • 30. import java.util.ArrayList; class Main { public static void main(String[] args) { // create an array list to store Integer data ArrayList<Integer> list1 = new ArrayList<>(); list1.add(4); list1.add(5); System.out.println("ArrayList of Integer: " + list1); // creates an array list to store String data ArrayList<String> list2 = new ArrayList<>(); list2.add("Four"); list2.add("Five"); System.out.println("ArrayList of String: " + list2); // creates an array list to store Double data ArrayList<Double> list3 = new ArrayList<>(); list3.add(4.5); list3.add(6.5); System.out.println("ArrayList of Double: " + list3); } } Output ArrayList of Integer: [4, 5] ArrayList of String: [Four, Five] ArrayList of Double: [4.5, 6.5]
  • 31. • we have used the same ArrayList class to store elements of Integer, String, and Double types. This is possible because of Java Generics. • Here, notice the line, • ArrayList<Integer> list1 = new ArrayList<>(); We have used Integer inside the angle brackets, <>. The angle bracket, <> is known as the type parameter in generics. • The type parameter is used to specify the type of objects (data) that the generics class or method works on.