Java Collection Framework
Java Collection Framework
Any group of individual objects which are represented as a single unit is known as the
collection of the objects. In Java, a separate framework named the “Collection Framework” has
been defined in JDK 1.2 which holds all the collection classes and interface in it.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main
“root” interfaces of Java collection classes.
Framework
A framework is a set of classes and interfaces which provide a ready-made architecture. In
order to implement a new feature or a class, there is no need to define a framework. However, 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.
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods
for grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these
collections had no common interface. Therefore, though the main aim of all the collections is the
same, the implementation of all these collections was defined independently and had no correlation
among them. And also, it is very difficult for the users to remember all the different methods, syntax,
and constructors present in every collection class.
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).
The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Java Collections
Iterator<T> iterator()
Linked List: Linked List class is an implementation of the Linked List data structure which is a
linear data structure where the elements are not stored in contiguous locations and every element
is a separate object with a data part and address part . The elements are linked using pointers and
addresses. Each element is known as a node.
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.
Example program on Linked List
import java.util.*;
public class LinkedList1{
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());
Java Sets
The Set interface of the Java Collections framework provides the features of the mathematical set in
Java. It extends the Collection interface.
HashSet
LinkedHashSet
EnumSet
TreeSet
Set Operations
The Java Set interface allows us to perform basic mathematical set operations like union, intersection,
and subset.
Union - to get the union of two sets x and y, we can use x.addAll(y)
Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)
HashSet
This class implements the Set interface, backed by a hash table (actually a HashMap
instance). It makes no guarantees as to the iteration order of the set; in particular, it does not
guarantee that the order will remain constant over time. This class permits the null element. This
class is not synchronized.
HashMap
Hashing :It is the process of converting an object into an integer value. The integer value helps in
indexing and faster searches.
HashMap : HashMap is a part of the Java collection framework. It uses a technique called Hashing.
It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains
an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data
structure internally for storing Key and Value.
int hash
K key
V value
Node next
Hashing
Hashing is a process of converting an object into integer form by using the method
hashCode(). Its necessary to write hashCode() method properly for better performance of HashMap
hashCode( ) : is used to get the hash Code of an object. hashCode() method of object class returns
the memory reference of object in integer form. Definition of hashCode() method is public native
hashCode(). It indicates the implementation of hashCode() is native because there is not any direct
method in java to fetch the reference of object. It is possible to provide your own implementation of
hashCode().
In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index.
equals( ) : equals method is used to check that 2 objects are equal or not. This method is provided by
Object class. You can override this in your class to provide your own implementation.
HashMap uses equals() to compare the key whether are equal or not. If equals() method return true,
they are equal otherwise not equal.
Buckets :A bucket is one element of HashMap array. It is used to store nodes. Two or more nodes
can have the same bucket. In that case link list structure is used to connect the nodes. Buckets are
different in capacity. A relation between bucket and capacity is as follows:
A single bucket can have more than one nodes, it depends on hashCode() method. The better your
hashCode() method is, the better your buckets will be utilized.
import java.util.Map;
import java.util.HashMap;
class Main {
numbers.put("One", 1);
numbers.put("Two", 2);
Hash Table: a hash table is a data structure that implements an associative array abstract data type, a
structure that can map keys to values. A hash table uses a hash function to compute an index, also
called a hash code, into an array of buckets or slots, from which the desired value can be found.
1. HashSet doesn’t maintain any order, the elements would be returned in any random order.
2. HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value
would be overwritten.
3. HashSet allows null values however if you insert more than one nulls it would still return only
one null value.
4. HashSet is non-synchronized.
5. The iterator returned by this class is fail-fast which means iterator would
throw ConcurrentModificationException if HashSet has been modified after creation of
iterator, by any means except iterator’s own remove method.
HashSet Methods:
1. boolean add(Element e) : It adds the element e to the list.
2. void clear() : It removes all the elements from the list.
3. Object clone() : This method returns a shallow copy of the HashSet.
4. boolean contains(Object o) : It checks whether the specified Object o is present in the list or
not. If the object has been found it returns true else false.
5. boolean isEmpty() : Returns true if there is no element present in the Set.
6. int size() : It gives the number of elements of a Set.
7. Boolean remove(Object o) : It removes the specified Object o from the Set.
HashSet Example
import java.util.HashSet;
public class HashSetExample {
// HashSet declaration
hset.add("Apple");
hset.add("Mango");
hset.add("Grapes");
hset.add("Orange");
hset.add("Fig");
hset.add("Apple");
hset.add("Mango");
hset.add(null);
hset.add(null);
System.out.println(hset);
Note: As you can see there all the duplicate values are not present in the output including the
duplicate null value.
Linked HashSet
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List
across all elements. When the iteration order is needed to be maintained this class is used. When
iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through
the elements in the order in which they were inserted. When cycling through LinkedHashSet using an
iterator, the elements will be returned in the order in which they were inserted.
Example program
import java.util.*;
public class LinkedHashSetEx
{
public static void main(String[] args)
{
LinkedHashSet<String> linkedset = new LinkedHashSet<String>();
// Adding element to LinkedHashSet
linkedset.add("A");
linkedset.add("B");
linkedset.add("C");
linkedset.add("D");
// This will not add new element as A already exists
linkedset.add("A");
linkedset.add("E");
System.out.println("Size of LinkedHashSet = " + linkedset.size());
System.out.println("Original LinkedHashSet:" + linkedset);
System.out.println("Removing D from LinkedHashSet: " + linkedset.remove("D"));
System.out.println("Trying to Remove Z which is not "+ "present: " + linkedset.remove("Z"));
System.out.println("Checking if A is present=" + linkedset.contains("A"));
System.out.println("Updated LinkedHashSet: " + linkedset);
}
}
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non
synchronized classes.
However, there are many differences between ArrayList and LinkedList classes that are given below.
ArrayList LinkedList
1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly linked
store the elements. list to store the elements.
2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses an array. If any element is removed ArrayList because it uses a doubly linked list,
from the array, all the bits are shifted in memory. so no bit shifting is required in memory.
3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
List Vs Set
List and Set both are interfaces. They both extends Collection interface.
The differences between List and Set interfaces in java.
1) List is an ordered collection it maintains the insertion order, which means upon displaying the list
content it will display the elements in the same order in which they got inserted into the list.
Set is an unordered collection, it doesn’t maintain any order. There are few implementations of Set
which maintains the order such as LinkedHashSet (It maintains the elements in insertion order).
2) List allows duplicates while Set doesn’t allow duplicate elements.
All the elements of a Set should be unique if you try to insert the duplicate element in Set it
would replace the existing value.
3) List implementations: ArrayList, LinkedList etc.
Set implementations: HashSet, LinkedHashSet, TreeSet etc.
4) List allows any number of null values.
Set can have only a single null value at most.
5) ListIterator can be used to traverse a List in both the directions(forward and backward)
However it cannot be used to traverse a Set. We can use Iterator (It works with List too) to
traverse a Set.
6) List interface has one legacy class called Vector whereas Set interface does not have any legacy
class.
When to use Set and When to use List?
The usage is purely depends on the requirement:
If the requirement is to have only unique values then Set is your best bet as any implementation of Set
maintains unique values only.
If there is a need to maintain the insertion order irrespective of the duplicity then List is a best option.
Both the implementations of List interface – ArrayList and LinkedList sorts the elements in their
insertion order.
Output:
ll.add("Kevin"); try{
ll.add("Kate"); hset.add(count[i]);
} Output:
Map interface
The Map interface of the Java collections framework provides the functionality of the map data
structure.
Working of Map
In Java, elements of Map are stored in key/value pairs. Keys are unique values associated with
individual Values. A map cannot contain duplicate keys. And, each key is associated with a single
value.
We can access and modify values using the keys associated with them. In the above diagram, we have
values: United States, Brazil, and Spain. And we have corresponding keys: us, br, and es.
In order to use functionalities of the Map interface, we can use these classes:
HashMap
EnumMap
LinkedHashMap
WeakHashMap
TreeMap
These classes are defined in the collections framework and implement the Map interface.
A Map cannot contain duplicate keys and each key can map to at most one value. Some
implementations allow null key and null value like the HashMap and LinkedHashMap, but some do
not like the TreeMap.
The order of a map depends on the specific implementations. For example, TreeMap and
LinkedHashMap have predictable order, while HashMap does not.
There are two interfaces for implementing Map in java. They are, Map and SortedMap, and three
classes: HashMap, TreeMap and LinkedHashMap.
Maps are perfect to use for key-value association mapping such as dictionaries. The maps are
used to perform lookups by keys or when someone wants to retrieve and update elements by keys.
Since Map is an interface, objects cannot be created of the type map. We always need a class which
extends this map in order to create an object. And also, after the introduction of Generics in Java 1.5,
it is possible to restrict the type of object that can be stored in the Map. This type-safe map can be
defined as:
Java Iterator
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is
called an "iterator" because "iterating" is the technical term for looping.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
public boolean hasNext( ) It returns true if the iterator has more elements otherwise it returns
false.
public Object next( ) It returns the element and moves the cursor pointer to the next element.
public void remove( ) It removes the last elements returned by the iterator. It is less used.
Example program
import java.util.ArrayList;
import java.util.Iterator;
// Make a collection
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Iterator<String> it = cars.iterator();
System.out.println(it.next());
while(it.hasNext()) {
System.out.println(it.next());
List Iterator
The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements
in this list (in proper sequence). The returned list iterator is fail-fast.
Syntax:
Return Value: This method returns a list iterator over the elements in this list (in proper sequence).
Methods of ListIterator
1) void add(E e): Inserts the specified element into the list (optional operation).
2) boolean hasNext(): Returns true if this list iterator has more elements when traversing the list in the
forward direction.
3) boolean hasPrevious(): Returns true if this list iterator has more elements when traversing the list
in the reverse direction.
4) E next(): Returns the next element in the list and advances the cursor position.
5) int nextIndex(): Returns the index of the element that would be returned by a subsequent call to
next().
6) E previous(): Returns the previous element in the list and moves the cursor position backwards.
7) int previousIndex(): Returns the index of the element that would be returned by a subsequent call
to previous().
8) void remove(): Removes from the list the last element that was returned by next() or previous()
(optional operation).
9) void set(E e): Replaces the last element returned by next() or previous() with the specified element
(optional operation).
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
names.add("Ram");
names.add("Raja");
names.add("Praveen");
names.add("Tulasi");
names.add("Kiran");
litr=names.listIterator();
while(litr.hasNext()){
System.out.println(litr.next());
while(litr.hasPrevious()){
System.out.println(litr.previous());
}}
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is
used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
There are various classes that implement the Queue interface, some of them are
Deque Interface:
This is a very slight variation of the queue data structure. Deque, also known as a double-ended
queue, is a data structure where we can add and remove the elements from both ends of the queue.
This interface extends the queue interface. The class which implements this interface is ArrayDeque.
Since ArrayDeque class implements the Deque interface, we can instantiate a deque object with this
class. For example,
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to
be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.
import java.util.*;
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
queue.remove();
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
} } }
ArrayDeque:
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue,
we can add or delete the elements from both the ends. ArrayDeque is faster than ArrayList and Stack
and has no capacity restrictions.
import java.util.*;
de_que.add(20);
de_que.add(30);
de_que.add(40);
de_que.add(50);
System.out.println(de_que);
de_que.clear(); // clear() method
de_que.addFirst(564);
de_que.addFirst(291);
de_que.addLast(14);
System.out.println(de_que);
}}
Java Comparable interface is used to order the objects of the user-defined class. This interface
is found in java.lang package and contains only one method named compareTo(Object). It provides a
single sorting sequence only, i.e., you can sort the elements on the basis of single data member only.
public int compareTo(Object obj): It is used to compare the current object with the specified object. It
returns
positive integer, if the current object is greater than the specified object.
negative integer, if the current object is less than the specified object.
In this method, we are going to implement the Comparable interface from java.lang Package
in the Pair class.
The Comparable interface contains the method compareTo to decide the order of the elements.
Override the compareTo method in the Pair class.
Create an array of Pairs and populate the array.
Use the Arrays.sort() function to sort the array.
Given an array of Pairs consisting of two fields of type string and integer. you have to sort the
array in ascending Lexicographical order and if two strings are the same sort it based on their
integer value.
Example 1
import java.io.*;
import java.util.*;
String x;
int y;
this.x = x;
this.y = y;
return this.x.compareTo(a.x);
else
return this.y - a.y; // we compare int values if the strings are equal
int n = 4;
Arrays.sort(arr);
System.out.println(arr[i]);
} }}
Comparator interface
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
public int compare(Object obj1, Object obj2): It compares the first object with the second object.
public boolean equals(Object obj): It is used to compare the current object with the specified object.
public boolean equals(Object obj): It is used to compare the current object with the specified object.