SlideShare una empresa de Scribd logo
1 de 56
Descargar para leer sin conexión
Advanced Java Programming
Topic: Collections
By
Ravi Kant Sahu
Asst. Professor, LPU
Contents
 Introduction
 Sets
 Comparator
 List
 Vector
 Stack
 Queue
 Map
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
 A collection is simply an object that groups multiple
elements into a single unit.
 Collections are used to store, retrieve, manipulate, and
communicate aggregate data.
 java.util package contains all the collection classes and
interfaces.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Collection Framework
 A collections framework is a unified architecture for
representing and manipulating collections.
 It is a collection of classes and interfaces.
 At the top of collection framework hierarchy, there is an
interface, Collection.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Advantages of Collections
 Reduces programming effort
 Increases program speed and quality
 Allows interoperability among unrelated APIs
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Collection Interfaces
The Java Collections Framework supports two types of containers:
1. Collection: for storing a collection of elements
2. Map: for storing key/value pairs
 Sets store a group of non-duplicate elements.
 Lists store an ordered collection of elements.
 Queues store objects that are processed in first-in, first-out
fashion.
 Maps are efficient data structures for quickly searching an
element using a key.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Collection Interfaces
 The AbstractCollection class provides partial implementation
for the Collection interface.
 It implements all the methods in Collection except the size()
and iterator() methods.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ColleCtion
Interface
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
boolean add(Object o)
 Appends the specified element o to the end of the collection.
boolean addAll(Collection c )
 Appends all of the elements in the specified collection to the
end of the collection.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Collection Interface
boolean contains(Object o)
 Returns true if this list contains the specified element.
boolean containsAll(Collection c)
 Returns true if this collection contains all the elements in c.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
boolean remove(Object o)
 Removes the element o from this collection.
boolean removeAll(Collection c)
 Removes all the elements in c from this collection.
boolean retainAll(Collection c)
 Retains the elements that are both in c and in this collection.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
void clear()
 Removes all of the elements from the collection.
boolean isEmpty()
 Returns true if this collection contains no elements.
int size()
 Returns the number of elements in the collection.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
object [] toArray()
 Returns an array of Object for the elements in the collection.
int hashCode()
 Returns the hash code for the collection.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Iterators
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Iterator
 There is an Iterable interface at the top of Collection hierarchy.
 The Collection interface extends the Iterable interface.
 It defines a method which returns an Iterator object for the
elements of Collection.
Iterator iterator()
 Iterator object is used to traverse the elements in a collection.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Iterator Interface
boolean hasNext()
Returns true if this iterator has more elements to traverse.
Object next()
Returns the next element from this iterator.
void remove()
Removes the last element obtained using the next method.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ListIterator
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ListIterator
 ListIterator is derived from Iterator interface and comes with
more methods than Iterator.
 ListIterator can be used to traverse for List type Objects.
 Allows to traverse in both the directions.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ListIterator Methods
 public abstract boolean hasPrevious()
 public abstract Object previous();
 public abstract int nextIndex();
 public abstract int previousIndex();
 public abstract void set(Object);
 public abstract void add(Object);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
list interface
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
List
 The List interface extends the Collection interface.
 It defines a collection for storing elements in a sequential order.
 It define an ordered collection with duplicates allowed.
 ArrayList , Vector and LinkedList are the sub-classes of List
interface.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of List Interface
 boolean add(int index, Object o )
 boolean addAll(int index, Collection c )
 Object remove(int index)
 Object get(int index)
 Object set(int index, Object o)
 int indexOf(Object o)
 int lastIndexOf(Object o)
 ListIterator listIterator()
 ListIterator listIterator(int start_index)
 List subList(int start_index, int end_index): returns a sublist from
start_index to end_index-1
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Sub-classes of List
 ArrayList
 LinkedList
 Vector
 Stack
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Set Interface
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Set Interface
 A set is an efficient data structure for storing and processing
non-duplicate elements.
 Set does not introduce new methods or constants.
 The sub-classes of Set (HashSet, TreeSet & LinkedHashSet)
ensure that no duplicate elements can be added to the set.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Set Interface
 The AbstractSet class provides implementations for the
equals() method and the hashCode().
 The hash code of a set is the sum of the hash codes of all the
elements in the set.
 The size() and iterator() are not implemented in the AbstractSet
class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Set ClaSSeS
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
HashSet
 The HashSet class is a concrete class that implements Set.
 A HashSet can be used to store duplicate-free elements.
 The load factor measures how full the set is allowed to be
before its capacity is increased.
 The load factor is a value between 0.0 and 1.0.
 When the number of elements exceeds the product of the
capacity and load factor, the capacity is automatically doubled.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
HashSet
 Constructors:
HashSet()
HashSet(Collection c)
HashSet(int Capacity)
HashSet(int capacity, float loadFactor)
 Note: By default, the initial capacity is 16 and the load factor is
0.75.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LinkedHashSet
 There is no particular order for the elements in a hash set.
 LinkedHashSet extends HashSet with linked-list
implementation that supports an ordering of the elements in the
set.
 Constructors:
LinkedHashSet()
LinkedHashSet(Collection c)
LinkedHashSet(int Capacity)
LinkedHashSet(int capacity, float loadFactor)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
SortedSet Interface
 SortedSet is a subinterface of Set, which guarantees that
the elements in the set are sorted.
 It provides the methods first() and last() for returning the
first and last elements in the set.
 headSet(toElement) and tailSet(fromElement) for returning
a portion of the set whose elements are less than
toElement and greater than or equal to fromElement.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
NevigableSet Interface
 NavigableSet extends SortedSet.
 It provides navigation methods lower(e), floor(e), ceiling(e),
and higher(e) that return elements respectively less than, less
than or equal, greater than or equal, and greater than a given
element and return null if there is no such element.
 The pollFirst() and pollLast() methods remove and return the
first and last element in the tree set, respectively.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
TreeSet
 TreeSet implements the SortedSet interface.
 We can add objects into a tree set as long as they can be
compared with each other.
 Constructor:
TreeSet()
TreeSet(Collection c)
TreeSet(Comparator c)
TreeSet(SortedSet s)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MAP InterfAce
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MAP
 A map is a container object that stores a collection of key/value
pairs.
 Keys are like indexes in List but in Map, the keys can be any
objects.
 A map cannot contain duplicate keys.
 Each key maps to one value.
 A key and its corresponding value form an entry stored in a map.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MAP
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MAP Methods
 int size()
 void clear()
 boolean isEmpty()
 V put( K key, V value)
 void putAll( m: Map<? extends K,? extendsV>)
 boolean containsKey (Object key)
 boolean containsValue(Object value)
 V get(Object key)
 Set<K> keySet()
 V remove( Object key)
 Collection <V> values()
 Set<Map.Entry<K,V>> entrySet()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MAP Class Hierarchy
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MAP
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
HashMap
 The HashMap class is efficient for locating a value, inserting an
entry, and deleting an entry.
 The entries in a HashMap are not ordered.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LinkedHashMap
 LinkedHashMap extends HashMap with a linked-list
implementation that supports an ordering of the entries in the map.
 The entries in a LinkedHashMap can be retrieved in two orders:
1. Order in which they were inserted into the map (insertion
order)
2. In the order in which they were last accessed, from least
recently to most recently accessed (access order).
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LinkedHashMap
 The no-arg constructor constructs a LinkedHashMap with the
insertion order.
 To construct a LinkedHashMap with the access order, use
LinkedHashMap(initialCapacity, loadFactor, true)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
TreeMap
 The TreeMap class is efficient for traversing the keys in a sorted
order.
 The keys can be sorted using the Comparable interface or the
Comparator interface.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
 If we create a TreeMap using its no-arg constructor, the
compareTo method in the Comparable interface is used to
compare the keys in the map.
 To use a comparator, we have to use the
TreeMap(Comparator comparator)
constructor to create a sorted map that uses the compare method
in the comparator to order the entries in the map based on the
keys.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
TreeMap
 SortedMap is a subinterface of Map, which guarantees that the
entries in the map are sorted.
 It provides the following methods:
 firstKey() and lastKey() for returning the first and last keys in the
map
 headMap(toKey) and tailMap(fromKey) for returning a portion of
the map whose keys are less than toKey and greater than or equal to
fromKey.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
SortedMap
 NavigableMap extends SortedMap.
 It provides the following navigation methods:
 lowerKey(key)
 floorKey(key)
 ceilingKey(key)
 higherKey(key)
return keys respectively less than, less than or equal, greater
than or equal, and greater than a given key and return null if
there is no such key.
 The pollFirstEntry() and pollLastEntry() methods remove and
return the first and last entry in the tree map, respectively.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
NavigableMap
Queue
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Queue and Priority Queue
 A queue is a first-in, first-out data structure.
 Elements are appended to the end of the queue and are removed
from the beginning of the queue.
 In a priority queue, elements are assigned priorities.
 When accessing elements, the element with the highest priority is
removed first.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Queue Interface
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
 The offer method is used to add an element to the queue.
 This method is similar to the add method in the Collection
interface, but the offer method is preferred for queues.
 The poll and remove methods are similar, except that poll()
returns null if the queue is empty, whereas remove() throws an
exception.
 The peek and element methods are similar, except that peek()
returns null if the queue is empty, whereas element() throws an
exception.
Queue Methods
Deque Interface
 Deque supports element insertion and removal at both ends.
 The name deque is short for “double-ended queue” and is usually
pronounced “deck.”
 The Deque interface extends Queue with additional methods for
inserting and removing elements from both ends of the queue.
 The methods addFirst(e), removeFirst(), addLast(e), removeLast(),
getFirst(), and getLast() are defined in the Deque interface.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Priority Queue
 The priority queue orders its elements according to their natural
ordering using Comparable.
 The element with the least value is assigned the highest priority
and thus is removed from the queue first.
 If there are several elements with the same highest priority, the tie
is broken arbitrarily.
 We can also specify an ordering using Comparator in the
constructor
PriorityQueue(initialCapacity, comparator)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Priority Queue
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Collection framework

Más contenido relacionado

La actualidad más candente

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 

La actualidad más candente (20)

Java collection
Java collectionJava collection
Java collection
 
Java packages
Java packagesJava packages
Java packages
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Java IO
Java IOJava IO
Java IO
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Namespaces
NamespacesNamespaces
Namespaces
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in java
 
Java Beans
Java BeansJava Beans
Java Beans
 
Array in Java
Array in JavaArray in Java
Array in Java
 

Destacado (16)

Servlets
ServletsServlets
Servlets
 
List classes
List classesList classes
List classes
 
Packages
PackagesPackages
Packages
 
Basic IO
Basic IOBasic IO
Basic IO
 
Internationalization
InternationalizationInternationalization
Internationalization
 
Swing api
Swing apiSwing api
Swing api
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
Jdbc
JdbcJdbc
Jdbc
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Networking
NetworkingNetworking
Networking
 
Event handling
Event handlingEvent handling
Event handling
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Generics
GenericsGenerics
Generics
 

Similar a Collection framework

Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
eyemitra1
 

Similar a Collection framework (20)

Java collections
Java collectionsJava collections
Java collections
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Java.util
Java.utilJava.util
Java.util
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Java beans
Java beansJava beans
Java beans
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Hash set (java platform se 8 )
Hash set (java platform se 8 )Hash set (java platform se 8 )
Hash set (java platform se 8 )
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
Inheritance
InheritanceInheritance
Inheritance
 
LJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptxLJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptx
 

Más de Ravi_Kant_Sahu (14)

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
 
Gui programming (awt)
Gui programming (awt)Gui programming (awt)
Gui programming (awt)
 
Event handling
Event handlingEvent handling
Event handling
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Packages
PackagesPackages
Packages
 
Array
ArrayArray
Array
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

Collection framework

  • 1. Advanced Java Programming Topic: Collections By Ravi Kant Sahu Asst. Professor, LPU
  • 2. Contents  Introduction  Sets  Comparator  List  Vector  Stack  Queue  Map Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. Introduction  A collection is simply an object that groups multiple elements into a single unit.  Collections are used to store, retrieve, manipulate, and communicate aggregate data.  java.util package contains all the collection classes and interfaces. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Collection Framework  A collections framework is a unified architecture for representing and manipulating collections.  It is a collection of classes and interfaces.  At the top of collection framework hierarchy, there is an interface, Collection. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Advantages of Collections  Reduces programming effort  Increases program speed and quality  Allows interoperability among unrelated APIs Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) Collection Interfaces The Java Collections Framework supports two types of containers: 1. Collection: for storing a collection of elements 2. Map: for storing key/value pairs
  • 7.
  • 8.  Sets store a group of non-duplicate elements.  Lists store an ordered collection of elements.  Queues store objects that are processed in first-in, first-out fashion.  Maps are efficient data structures for quickly searching an element using a key. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) Collection Interfaces
  • 9.  The AbstractCollection class provides partial implementation for the Collection interface.  It implements all the methods in Collection except the size() and iterator() methods. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. ColleCtion Interface Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. boolean add(Object o)  Appends the specified element o to the end of the collection. boolean addAll(Collection c )  Appends all of the elements in the specified collection to the end of the collection. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) Methods of Collection Interface
  • 12. boolean contains(Object o)  Returns true if this list contains the specified element. boolean containsAll(Collection c)  Returns true if this collection contains all the elements in c. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. boolean remove(Object o)  Removes the element o from this collection. boolean removeAll(Collection c)  Removes all the elements in c from this collection. boolean retainAll(Collection c)  Retains the elements that are both in c and in this collection. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. void clear()  Removes all of the elements from the collection. boolean isEmpty()  Returns true if this collection contains no elements. int size()  Returns the number of elements in the collection. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. object [] toArray()  Returns an array of Object for the elements in the collection. int hashCode()  Returns the hash code for the collection. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Iterators Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. Iterator  There is an Iterable interface at the top of Collection hierarchy.  The Collection interface extends the Iterable interface.  It defines a method which returns an Iterator object for the elements of Collection. Iterator iterator()  Iterator object is used to traverse the elements in a collection. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. Methods of Iterator Interface boolean hasNext() Returns true if this iterator has more elements to traverse. Object next() Returns the next element from this iterator. void remove() Removes the last element obtained using the next method. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. ListIterator Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. ListIterator  ListIterator is derived from Iterator interface and comes with more methods than Iterator.  ListIterator can be used to traverse for List type Objects.  Allows to traverse in both the directions. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. ListIterator Methods  public abstract boolean hasPrevious()  public abstract Object previous();  public abstract int nextIndex();  public abstract int previousIndex();  public abstract void set(Object);  public abstract void add(Object); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. list interface Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. List  The List interface extends the Collection interface.  It defines a collection for storing elements in a sequential order.  It define an ordered collection with duplicates allowed.  ArrayList , Vector and LinkedList are the sub-classes of List interface. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. Methods of List Interface  boolean add(int index, Object o )  boolean addAll(int index, Collection c )  Object remove(int index)  Object get(int index)  Object set(int index, Object o)  int indexOf(Object o)  int lastIndexOf(Object o)  ListIterator listIterator()  ListIterator listIterator(int start_index)  List subList(int start_index, int end_index): returns a sublist from start_index to end_index-1 Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. Sub-classes of List  ArrayList  LinkedList  Vector  Stack Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 26. Set Interface Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. Set Interface  A set is an efficient data structure for storing and processing non-duplicate elements.  Set does not introduce new methods or constants.  The sub-classes of Set (HashSet, TreeSet & LinkedHashSet) ensure that no duplicate elements can be added to the set. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. Set Interface  The AbstractSet class provides implementations for the equals() method and the hashCode().  The hash code of a set is the sum of the hash codes of all the elements in the set.  The size() and iterator() are not implemented in the AbstractSet class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. Set ClaSSeS Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. HashSet  The HashSet class is a concrete class that implements Set.  A HashSet can be used to store duplicate-free elements.  The load factor measures how full the set is allowed to be before its capacity is increased.  The load factor is a value between 0.0 and 1.0.  When the number of elements exceeds the product of the capacity and load factor, the capacity is automatically doubled. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 31. HashSet  Constructors: HashSet() HashSet(Collection c) HashSet(int Capacity) HashSet(int capacity, float loadFactor)  Note: By default, the initial capacity is 16 and the load factor is 0.75. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 32. LinkedHashSet  There is no particular order for the elements in a hash set.  LinkedHashSet extends HashSet with linked-list implementation that supports an ordering of the elements in the set.  Constructors: LinkedHashSet() LinkedHashSet(Collection c) LinkedHashSet(int Capacity) LinkedHashSet(int capacity, float loadFactor) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 33. SortedSet Interface  SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted.  It provides the methods first() and last() for returning the first and last elements in the set.  headSet(toElement) and tailSet(fromElement) for returning a portion of the set whose elements are less than toElement and greater than or equal to fromElement. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 34. NevigableSet Interface  NavigableSet extends SortedSet.  It provides navigation methods lower(e), floor(e), ceiling(e), and higher(e) that return elements respectively less than, less than or equal, greater than or equal, and greater than a given element and return null if there is no such element.  The pollFirst() and pollLast() methods remove and return the first and last element in the tree set, respectively. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 35. TreeSet  TreeSet implements the SortedSet interface.  We can add objects into a tree set as long as they can be compared with each other.  Constructor: TreeSet() TreeSet(Collection c) TreeSet(Comparator c) TreeSet(SortedSet s) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 36. MAP InterfAce Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 37. MAP  A map is a container object that stores a collection of key/value pairs.  Keys are like indexes in List but in Map, the keys can be any objects.  A map cannot contain duplicate keys.  Each key maps to one value.  A key and its corresponding value form an entry stored in a map. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 38. MAP Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 39. MAP Methods  int size()  void clear()  boolean isEmpty()  V put( K key, V value)  void putAll( m: Map<? extends K,? extendsV>)  boolean containsKey (Object key)  boolean containsValue(Object value)  V get(Object key)  Set<K> keySet()  V remove( Object key)  Collection <V> values()  Set<Map.Entry<K,V>> entrySet() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 40. MAP Class Hierarchy Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 41. MAP Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 42. HashMap  The HashMap class is efficient for locating a value, inserting an entry, and deleting an entry.  The entries in a HashMap are not ordered. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 43. LinkedHashMap  LinkedHashMap extends HashMap with a linked-list implementation that supports an ordering of the entries in the map.  The entries in a LinkedHashMap can be retrieved in two orders: 1. Order in which they were inserted into the map (insertion order) 2. In the order in which they were last accessed, from least recently to most recently accessed (access order). Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 44. LinkedHashMap  The no-arg constructor constructs a LinkedHashMap with the insertion order.  To construct a LinkedHashMap with the access order, use LinkedHashMap(initialCapacity, loadFactor, true) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 45. TreeMap  The TreeMap class is efficient for traversing the keys in a sorted order.  The keys can be sorted using the Comparable interface or the Comparator interface. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 46.  If we create a TreeMap using its no-arg constructor, the compareTo method in the Comparable interface is used to compare the keys in the map.  To use a comparator, we have to use the TreeMap(Comparator comparator) constructor to create a sorted map that uses the compare method in the comparator to order the entries in the map based on the keys. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) TreeMap
  • 47.  SortedMap is a subinterface of Map, which guarantees that the entries in the map are sorted.  It provides the following methods:  firstKey() and lastKey() for returning the first and last keys in the map  headMap(toKey) and tailMap(fromKey) for returning a portion of the map whose keys are less than toKey and greater than or equal to fromKey. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) SortedMap
  • 48.  NavigableMap extends SortedMap.  It provides the following navigation methods:  lowerKey(key)  floorKey(key)  ceilingKey(key)  higherKey(key) return keys respectively less than, less than or equal, greater than or equal, and greater than a given key and return null if there is no such key.  The pollFirstEntry() and pollLastEntry() methods remove and return the first and last entry in the tree map, respectively. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) NavigableMap
  • 49. Queue Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 50. Queue and Priority Queue  A queue is a first-in, first-out data structure.  Elements are appended to the end of the queue and are removed from the beginning of the queue.  In a priority queue, elements are assigned priorities.  When accessing elements, the element with the highest priority is removed first. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 51. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) Queue Interface
  • 52. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)  The offer method is used to add an element to the queue.  This method is similar to the add method in the Collection interface, but the offer method is preferred for queues.  The poll and remove methods are similar, except that poll() returns null if the queue is empty, whereas remove() throws an exception.  The peek and element methods are similar, except that peek() returns null if the queue is empty, whereas element() throws an exception. Queue Methods
  • 53. Deque Interface  Deque supports element insertion and removal at both ends.  The name deque is short for “double-ended queue” and is usually pronounced “deck.”  The Deque interface extends Queue with additional methods for inserting and removing elements from both ends of the queue.  The methods addFirst(e), removeFirst(), addLast(e), removeLast(), getFirst(), and getLast() are defined in the Deque interface. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 54. Priority Queue  The priority queue orders its elements according to their natural ordering using Comparable.  The element with the least value is assigned the highest priority and thus is removed from the queue first.  If there are several elements with the same highest priority, the tie is broken arbitrarily.  We can also specify an ordering using Comparator in the constructor PriorityQueue(initialCapacity, comparator) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 55. Priority Queue Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)