Collection Framework
Collection Framework
Outline
Collection
List Interface
Iterator
Comparator
Vector Class
Stack
Queue
List v/s Sets
Map Interfaces
Collection
• The Collection in Java is a framework that provides an
architecture to store and manipulate the group of objects.
• Java Collections can achieve all the operations that you perform
on a data such as searching, sorting, insertion, manipulation,
and deletion.
• Java Collection means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque)
and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
Hierarchy of
Collection
Framework
Collection Interface - Methods
Sr. Method & Description
1 boolean add(E e)
It is used to insert an element in this collection.
3 void clear()
It removes the total number of elements from the collection.
5 boolean containsAll(Collection<?> c)
It is used to search the specified collection in the collection.
7 int hashCode()
Returns the hashcode for the invoking collection.
Collection Interface – Methods (Cont.)
Sr. Method & Description
8 boolean isEmpty()
Returns true if the invoking collection is empty. Otherwise returns
false.
9 Iterator iterator()
It returns an iterator.
11 boolean removeAll(Collection<?> c)
It is used to delete all the elements of the specified collection from
the invoking collection.
12 boolean retainAll(Collection<?> c)
It is used to delete all the elements of invoking collection except the
specified collection.
13 int size()
It returns the total number of elements in the collection.
List Interface
• The List interface extends Collection and declares the
behavior of a collection that stores a sequence of elements.
• Elements can be inserted or accessed by their position in the
list, using a zero-based index.
• A list may contain duplicate elements.
• List is a generic interface with following declaration
interface List<E>
where E specifies the type of object.
List Interface - Methods
Sr. Method & Description
1 void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in index. Any
pre-existing elements at or beyond the point of insertion are shifted
up. Thus, no elements are overwritten.
1 boolean empty()
Returns true if the stack is empty, and returns false if the stack
contains elements.
2 E peek()
Returns the element on the top of the stack, but does not remove
it.
3 E pop()
Returns the element on the top of the stack, removing it in the
process.
4 E push(E element)
Pushes element onto the stack. Element is also returned.
1 E element()
Returns the element at the head of the queue. The element is not
removed. It throws NoSuchElementException if the queue is
empty.
3 E peek()
Returns the element at the head of the queue. It returns null if the
queue is empty. The element is not removed.
4 E poll()
Returns the element at the head of the queue, removing the
element in the process. It returns null if the queue is empty.
5 E remove()
Returns the element at the head of the queue, returning the
element in the process. It throws NoSuchElementException if the
queue is empty.
Queue Example
import java.util.*;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> q = new LinkedList<String>();
q.add("Tom");
q.add("Jerry");
q.add("Mike");
q.add("Steve");
q.add("Harry");
System.out.println("Elements in Queue:"+q);
System.out.println("Removed element:
"+q.remove());
System.out.println("Head: "+q.element());
System.out.println("poll(): "+q.poll());
System.out.println("peek(): "+q.peek());
System.out.println("Elements in Queue:"+q);
}
}
PriorityQueue
• PriorityQueue extends AbstractQueue and implements the
Queue interface.
• It creates a queue that is prioritized based on the queue's
comparator.
• PriorityQueue is declared as follows:
PriorityQueue<E> = new PriorityQueue<E>;
• It builds an empty queue with starting capacity as 11.
PriorityQueue - Example
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> numbers = new
PriorityQueue<>();
numbers.add(750);
numbers.add(500);
numbers.add(900);
numbers.add(100);
while (!numbers.isEmpty()) {
System.out.println(numbers.remove());
}
}
}
List v/s Sets
List Set
Lists allow duplicates. Sets allow only unique
List is an ordered elements.
Sets is an unordered
collection.
Popular implementation of collection.
Popular implementation of
List interface includes Set interface includes
ArrayList, Vector and HashSet, TreeSet and
LinkedList. LinkedHashSet.
When to use List and Set?
Lists - If insertion order is maintained during insertion and allows
duplicates.
Sets – If unique collection without any duplicates without
maintaining order.
Maps
• A map is an object that stores associations between keys and
values, or key/value pairs.
• Given a key, you can find its value. Both keys and values are
objects.
• The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others
cannot.
• Maps don't implement the Iterable interface. This means that
you cannot cycle through a map using a for-each style for loop.
Furthermore, you can’t obtain an iterator to a map.
Map Interfaces
Interface Description
Map Maps unique keys to values.
Map.Entry Describes an element (a key/value
pair) in a map. This is an inner class
of Map.
NavigableMap Extends SortedMap to handle the
retrieval of entries based on closest-
match searches.
SortedMap Extends Map so that the keys are
maintained in ascending order.
Map Classes
Class Description
AbstractMap Implements most of the Map
interface.
EnumMap Extends AbstractMap for use with
enum keys.
HashMap Extends AbstractMap to use a hash
table.
TreeMap Extends AbstractMap to use a tree.
WeakHashMap Extends AbstractMap to use a hash
table with weak keys.
LinkedHashMap Extends HashMap to allow insertion-
order iterators.
IdentityHashMa Extends AbstractMap and uses
p reference equality when comparing
HashMap Class
• The HashMap class extends AbstractMap and implements the
Map interface.
• It uses a hash table to store the map. This allows the execution
time of get() and put() to remain constant even for large sets.
• HashMap is a generic class that has declaration:
class HashMap<K,V>
HashMap - Constructors
Sr Constructor & Description
.
1 HashMap()
Constructs an empty HashMap with the default initial capacity
(16) and the default load factor (0.75).
2 HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial
capacity and the default load factor (0.75).
3 HashMap(int initialCapacity, float loadFactor)
Constructs an empty HashMap with the specified initial
capacity and load factor.
4 HashMap(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the
specified Map.
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map.
HashMap<String, Double> hm = new HashMap<String, Double>();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Tod Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>> set = hm.entrySet();
// Display the set.
for(Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
//Deposit 1000 into John Doe's account.
double balance = hm.get("John Doe");
hm.put("John Doe", balance + 1000);
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}