Java Collection Framework
Java Collection Framework
But, **we can solve this problem by using `Object` type arrays.**
```
Object [] a = new Object[10000]; a[0] = new Student(); a[1] = new Customer(); ```
• Arrays is not implemented using some standard underlying Data Structures. So,
we do not get ready-made method support with arrays. For every requirement,
we need to implement logic of our own.
Example: If we need to insert elements into the array, and all elements should be
inserted in some sorting order. We have no method to perform this sorting logic
for us. We need to write our own.
Solution: Collections
• Collections are growable in nature. We can increase or decrease the size.
• Collections can hold homogeneous and heterogeneous objects.
• Every collection class is implemented based on some standard Data Structures and
it comes with ready-made methods. We need not implement on our own.
Collections in Java
Collections in java is a framework that provides an architecture to store and
manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
What is Collection framework
Collection framework represents a unified architecture for storing and
manipulating group of objects.
It has:
• Interfaces and its implementations i.e. classes
• Algorithm
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for Collection
framework.
ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It inherits
AbstractList class and implements List interface.
The important points about Java ArrayList class are:
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the index basis.
• In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.
Hierarchy of ArrayList class
}
}
Output:
iterating the elements after removing the elements of al2...
Vijay
Ajay
Example of retainAll() method
import java.util.*;
class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
System.out.println("iterating the elements after retaining the elements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
iterating the elements after retaining the elements of al2...
Ravi
LinkedList
Java LinkedList class uses 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:
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because no shifting needs to be
occurred.
• Java LinkedList class can be used as list, stack or queue.
Hierarchy of LinkedList class
System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
}
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
List
List Interface is the subinterface of Collection.It contains methods to insert and
delete elements in index basis.It is a factory of ListIterator interface.
List Interface declaration
public interface List<E> extends Collection<E>
Methods of Java List Interface
HashSet
Java HashSet class is used to create a collection that uses a hash table for storage.
It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.
Difference between List and Set
List can contain duplicate elements whereas Set contains unique elements only.
Hierarchy of HashSet class
HashSet class declaration
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable
Constructors of Java HashSet class
LinkedHashSet
Java LinkedHashSet class is a Hash table and Linked list implementation of the set
interface. It inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
• Contains unique elements only like HashSet.
• Provides all optional set operations, and permits null elements.
• Maintains insertion order.
Hierarchy of LinkedHashSet class
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. It
inherits AbstractSet class and implements NavigableSet interface. The objects of
TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
• Contains unique elements only like HashSet.
• Access and retrieval times are quiet fast.
• Maintains ascending order.
Hierarchy of TreeSet class
Queue
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO,
first element is removed first and last element is removed at last.
Queue Interface declaration
public interface Queue<E> extends Collection<E>
Methods of Java Queue Interface
PriorityQueue class
The PriorityQueue class provides the facility of using queue. But it does not orders
the elements in FIFO manner. It inherits AbstractQueue class.
PriorityQueue class declaration
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Java PriorityQueue Example
import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
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();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
Deque
Java Deque Interface is a linear collection that supports element insertion and
removal at both ends. Deque is an acronym for "double ended queue".
Deque Interface declaration
public interface Deque<E> extends Queue<E>
Methods of Java Deque Interface
ArrayDeque class
The ArrayDeque class provides the facility of using deque and resizable-array. It
inherits AbstractCollection class and implements the Deque interface.
The important points about ArrayDeque class are:
• Unlike Queue, we can add or remove elements from both sides.
• Null elements are not allowed in the ArrayDeque.
• ArrayDeque is not thread safe, in the absence of external synchronization.
• ArrayDeque has no capacity restrictions.
• ArrayDeque is faster than LinkedList and Stack.
ArrayDeque Hierarchy
Map
A map contains values on the basis of key i.e. key and value pair. Each key and
value pair is known as an entry. Map contains only unique keys.
Map is useful if you have to search, update or delete elements on the basis of key.
Useful methods of Map interface
Map.Entry Interface
Entry is the sub interface of Map. So we will be accessed it by Map.Entry name. It
provides methods to get key and value.
Methods of Map.Entry interface
HashMap
Java HashMap class implements the map interface by using a hashtable. It inherits
AbstractMap class and implements Map interface.
The important points about Java HashMap class are:
• A HashMap contains values based on the key.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It maintains no order.
Hierarchy of HashMap class
HashMap class declaration
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,
Cloneable, Serializable
HashMap class Parameters
• K: It is the type of keys maintained by this map.
• V: It is the type of mapped values.
Constructors of Java HashMap class
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
100 Amit
101 Vijay
102 Rahul
Java LinkedHashMap Example:remove()
import java.util.*;
public class LinkedHashMapExample {
public static void main(String args[]) {
// Create and populate linked hash map
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(101,"Let us C");
map.put(102, "Operating System");
map.put(103, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
Output:
Values before remove: {101=Let us C, 102=Operating System, 103=Data
Communication and Networking}
Values after remove: {101=Let us C, 103=Data Communication and Networking}
TreeMap
Java TreeMap class implements the Map interface by using a tree. It provides an
efficient means of storing key/value pairs in sorted order.
The important points about Java TreeMap class are:
• A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
• It contains only unique elements.
• It cannot have null key but can have multiple null values.
• It is same as HashMap instead maintains ascending order.
Hierarchy
Hashtable
Java Hashtable class implements a hashtable, which maps keys to values. It
inherits Dictionary class and implements the Map interface.
The important points about Java Hashtable class are:
• A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
• It contains only unique elements.
• It may have not have any null key or value.
• It is synchronized.
Hashtable class declaration
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>,
Cloneable, Serializable
Hashtable class Parameters
• K: It is the type of keys maintained by this map.
• V: It is the type of mapped values.
Constructors of Java Hashtable class
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Java Hashtable Example: remove()
import java.util.*;
public class HashtableExample {
public static void main(String args[]) {
// create and populate hash table
Hashtable<Integer, String> map = new Hashtable<Integer, String>();
map.put(102,"Let us C");
map.put(103, "Operating System");
map.put(101, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
Output:
Values before remove: {103=Operating System, 102=Let us C, 101=Data
Communication and Networking}
Values after remove: {103=Operating System, 101=Data Communication and
Networking}
EnumMap
Java EnumMap class is the specialized Map implementation for enum keys. It
inherits Enum and AbstractMap classes.
EnumMap class hierarchy
Collections class
Java collection class is used exclusively with static methods that operate on or
return collections. It inherits Object class.
The important points about Java Collections class are:
• Java Collection class supports the polymorphic algorithms that operate on
collections.
• Java Collection class throws a NullPointerException if the collections or class
objects provided to them are null.
Collections class declaration
public class Collections extends Object
Methods of Java Collections class
Java Collections Example
import java.util.*;
public class CollectionsExample {
public static void main(String a[]){
List<String> list = new ArrayList<String>();
list.add("C");
list.add("Core Java");
list.add("Advance Java");
System.out.println("Initial collection value:"+list);
Collections.addAll(list, "Servlet","JSP");
System.out.println("After adding elements collection value:"+list);
String[] strArr = {"C#", ".Net"};
Collections.addAll(list, strArr);
System.out.println("After adding array collection value:"+list);
}
}
Output:
Initial collection value:[C, Core Java, Advance Java]
After adding elements collection value:[C, Core Java, Advance Java, Servlet, JSP]
After adding array collection value:[C, Core Java, Advance Java, Servlet, JSP, C#,
.Net]
Java Collections Example: max()
import java.util.*;
public class CollectionsExample {
public static void main(String a[]){
List<Integer> list = new ArrayList<Integer>();
list.add(46);
list.add(67);
list.add(24);
list.add(16);
list.add(8);
list.add(12);
System.out.println("Value of maximum element from the collection:
"+Collections.max(list));
}
}
Output:
Value of maximum element from the collection: 67
Java Collections Example: min()
import java.util.*;
public class CollectionsExample {
public static void main(String a[]){
List<Integer> list = new ArrayList<Integer>();
list.add(46);
list.add(67);
list.add(24);
list.add(16);
list.add(8);
list.add(12);
System.out.println("Value of minimum element from the collection:
"+Collections.min(list));
}
}
Output:
Value of minimum element from the collection: 8
Sorting in Collection
We can sort the elements of:
• String objects
• Wrapper class objects
• User-defined class objects
Collections class provides static methods for sorting the elements of collection. If
collection elements are of Set type, we can use TreeSet. But we cannot sort the
elements of List. Collections class provides methods for sorting the elements of
List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List. List elements must
be of Comparable type.
Note: String class and Wrapper classes implements the Comparable interface. So,
if you store the objects of string or wrapper classes, it will be Comparable.
Example of Sorting the elements of List that contains string objects
import java.util.*;
class TestSort1{
public static void main(String args[]){
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Mukesh
Saurav
Tahir
Viru
Example of Sorting the elements of List that contains Wrapper class objects
import java.util.*;
class TestSort2{
public static void main(String args[]){
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
101
201
230
Comparable interface
Java Comparable interface is used to order the objects of user-defined class. This
interface is found in java.lang package and contains only one method
named compareTo(Object). It provide single sorting sequence only i.e. you can
sort the elements on based on single data member only. For example, it may
be rollno, name, age or anything else.
compareTo(Object obj) method
public int compareTo(Object obj): is used to compare the current object with the
specified object.
We can sort the elements of:
• String objects
• Wrapper class objects
• User-defined class objects
Collections class
Collections class provides static methods for sorting the elements of collections. If
collection elements are of Set or Map, we can use TreeSet or TreeMap. But we
cannot sort the elements of List. Collections class provides methods for sorting the
elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List. List elements must
be of Comparable type.
Note: String class and Wrapper classes implements Comparable interface by
default. So if you store the objects of string or wrapper classes in list, set or map, it
will be Comparable by default.
Java Comparable Example
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
105 Jai 21
101 Vijay 23
106 Ajay 27
Comparator interface
Java Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2
methods compare(Object obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements on the basis of
any data member, for example rollno, name, age or anything else.
compare() method
public int compare(Object obj1,Object obj2): compares the first object with
second object.
Collections class
Collections class provides static methods for sorting the elements of collection. If
collection elements are of Set or Map, we can use TreeSet or TreeMap. But we
cannot sort the elements of List. Collections class provides methods for sorting the
elements of List type elements also.
Method of Collections class for sorting List elements
public void sort(List list, Comparator c): is used to sort the elements of List by the
given Comparator.
Java Comparator Example (Non-generic Style)
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
class AgeComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
Java Comparator Example (Generic Style)
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
class AgeComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
import java.util.*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
return s1.name.compareTo(s2.name);
}
}
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27