Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

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

1. ArrayList 2. LinkedList 3. Vector 4. HashSet


5. LinkedHashSet 6. TreeSet 7. HashMap 8. TreeMap
9. LinkedHashMap 10. Hashtable

Hierarchy of Collection Framework


The java.util package contains all the classes and interfaces for the Collection framework.
Iterable Interface: The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

Iterator<T> iterator()

It returns the iterator over the elements of type T.

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());

//Removing specific element from arraylist


al.remove("Vijay");
System.out.println("After invoking remove(object) method: "+al);
//Removing element on the basis of specific position
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);
}
}

Java Sets
The Set interface of the Java Collections framework provides the features of the mathematical set in
Java. It extends the Collection interface.

Unlike the List interface, sets cannot contain duplicate elements.

Classes that implement Set


Since Set is an interface, we cannot create objects from it.In order to use functionalities of the Set
interface, we can use these classes:

 HashSet
 LinkedHashSet
 EnumSet
 TreeSet

Interfaces that extend Set


The set interface is also extended by these sub interfaces:
 SortedSet
 NavigableSet

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)

Subset - to check if x is a subset of y, we can use y.containsAll(x)

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.

There are four fields in HashMap.

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:

capacity = number of buckets * load factor

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.

//HashMap Example program

import java.util.Map;

import java.util.HashMap;

class Main {

public static void main(String[] args) {

// Creating a map using the HashMap

Map<String, Integer> numbers = new HashMap<>();

// Insert elements to the map

numbers.put("One", 1);

numbers.put("Two", 2);

System.out.println("Map: " + numbers);

// Access keys of the map

System.out.println("Keys: " + numbers.keySet());

// Access values of the map

System.out.println("Values: " + numbers.values());

// Access entries of the map

System.out.println("Entries: " + numbers.entrySet());


// Remove Elements from the map

int value = numbers.remove("Two");

System.out.println("Removed Value: " + value);

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.

Points to Note about HashSet:

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 {

public static void main(String args[]) {

// HashSet declaration

HashSet<String> hset = new HashSet<String>( );

// Adding elements to the HashSet

hset.add("Apple");

hset.add("Mango");

hset.add("Grapes");

hset.add("Orange");

hset.add("Fig");

//Addition of duplicate elements

hset.add("Apple");

hset.add("Mango");

//Addition of null values

hset.add(null);

hset.add(null);

//Displaying HashSet elements

System.out.println(hset);

[null, Mango, Grapes, Apple, Orange, Fig]

Note: As you can see there all the duplicate values are not present in the output including the
duplicate null value.

Difference between List and Set


A list can contain duplicate elements whereas Set contains unique elements only.

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.

LinkedHashSet<E> hs = new LinkedHashSet<E>();

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:

List Example ArrayList Elements:

import java.util.List; [Chaitanya, Rahul, Ajeet]

import java.util.ArrayList; LinkedList Elements:

import java.util.LinkedList; [Kevin, Peter, Kate]

public class ListExample {

public static void main(String[] args) { Set Example

List<String> al = new ArrayList<String>(); import java.util.Set;

al.add("Chaitanya"); import java.util.HashSet;

al.add("Rahul"); import java.util.TreeSet;

al.add("Ajeet"); public class SetExample {

System.out.println("ArrayList Elements: "); public static void main(String args[]) {

System.out.print(al); int count[] = {11, 22, 33, 44, 55};

List<String> ll = new LinkedList<String>(); Set<Integer> hset = new HashSet<Integer>();

ll.add("Kevin"); try{

ll.add("Peter"); for(int i = 0; i<4; i++)

ll.add("Kate"); hset.add(count[i]);

System.out.println("\nLinkedList Elements: "); System.out.println(hset);

System.out.print(ll); TreeSet<Integer> treeset = new


TreeSet<Integer>(hset);
}
System.out.println("The sorted list is:");
System.out.println(treeset); }

} Output:

catch(Exception e){ [33, 22, 11, 44]

e.printStackTrace(); The sorted list is:

} [11, 22, 33, 44]

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.

Now, we can access those values using their corresponding keys.

Note: The Map interface maintains 3 different sets:

 The set of keys


 The set of values
 The set of key/value associations (mapping).

Hence we can access keys, values, and associations individually.

Classes that implement Map

Since Map is an interface, we cannot create objects from it.

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.

Interfaces that extend Map

Characteristics of a 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.

Why and When to use Maps?

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.

Some examples are:

1. A map of error codes and their descriptions.


2. A map of zip codes and cities.
3. A map of managers and employees. Each manager (key) is associated with a list of employees
(value) he manages.
4. A map of classes and students. Each class (key) is associated with a list of students (value).

Creating Map Objects

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:

Obj is the type of the object to be stored in Map

Map hm = new HashMap ();

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.

Methods of Iterator interface

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.

To use an Iterator, you must import it from the java.util package.

Example program

// Import the ArrayList class and the Iterator class

import java.util.ArrayList;

import java.util.Iterator;

public class IteratorEx {

public static void main(String[] args) {

// Make a collection

ArrayList<String> cars = new ArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");
cars.add("Mazda");

// Get the iterator

Iterator<String> it = cars.iterator();

// Print the first item

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:

public ListIterator listIterator()

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).

List Iterator example program

import java.util.ArrayList;

import java.util.List;

import java.util.ListIterator;

public class ListIteratorEx {

public static void main(String[] args) {

ListIterator<String> litr = null;

List<String> names = new ArrayList<String>();

names.add("Ram");

names.add("Raja");

names.add("Praveen");

names.add("Tulasi");

names.add("Kiran");

//Obtaining list iterator

litr=names.listIterator();

System.out.println("Traversing the list in forward direction:");

while(litr.hasNext()){

System.out.println(litr.next());

System.out.println("\nTraversing the list in backward direction:");

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.

Queue interface can be instantiated as:

Queue<String> q1 = new PriorityQueue();

Queue<String> q2 = new ArrayDeque();

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,

Deque<T> ad = new ArrayDeque<> ();

Where T is the type of the object.

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.

Consider the following example.

import java.util.*;

public class PQueue{

public static void main(String args[]){

PriorityQueue<String> queue=new PriorityQueue<String>();

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();

System.out.println("after removing two elements:");

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.

Consider the following example.

import java.util.*;

public class ArrayDeque {

public static void main(String[] args)

ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(10);

de_que.add(10); // add() method to insert

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

// addFirst() method to insert the elements at the head

de_que.addFirst(564);

de_que.addFirst(291);

de_que.addLast(24); // addLast() method to insert the elements at the last

de_que.addLast(14);

System.out.println(de_que);

}}

Java Comparable interface

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.

For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method

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.

zero, if the current object is equal to the specified object.

Using Comparable Interface

 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.*;

class Pair implements Comparable<Pair> {

String x;

int y;

public Pair(String x, int y)

this.x = x;

this.y = y;

public String toString()

return "(" + x + "," + y + ")";

@Override public int compareTo(Pair a)

if (this.x.compareTo(a.x) != 0) // if the string are not equal

return this.x.compareTo(a.x);

else

return this.y - a.y; // we compare int values if the strings are equal

public class CompClass {

public static void main(String[] args)


{

int n = 4;

Pair arr[] = new Pair[n];

arr[0] = new Pair("abc", 3);

arr[1] = new Pair("a", 4);

arr[2] = new Pair("bc", 5);

arr[3] = new Pair("a", 2);

// Sorting the array

Arrays.sort(arr);

print(arr); // printing the Pair array

public static void print(Pair[] arr)

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

System.out.println(arr[i]);

} }}

Comparator interface

Java Comparator interface is used to order the objects of a user-defined class.

It contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).

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.

Methods of Java Comparator Interface

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.

You might also like