Module 1 - Collections Framework
Module 1 - Collections Framework
BCS402
The collections and Framework: Collections
Overview, The Collection Interfaces, The Collection
Classes, accessing a collection Via an Iterator, Storing
User Defined Classes in Collections, The Random
Access, Interface, Working with Maps, Comparators,
The Collection Algorithms, Arrays, The legacy Classes
and Interfaces, Parting Thoughts on Collections
Collection in Java
• 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 sear
• Java Collection framework provides many interfaces such as
• Set, List, Queue, Deque
• classes
• ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).
• Searching, sorting, insertion, manipulation, and deletion.
Collection in Java
• What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
Collection framework
boolean remove(Object key, Object value) It removes the specified values with the
associated specified keys from the map.
Methods in Map Interface
Set keySet() It returns the Set view containing
all the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view containing
all the keys and values.
void clear() It is used to reset the map.
boolean containsValue(Object value) This method returns true if some
value equal to the value exists within
the map, else return false.
boolean containsKey(Object key) This method returns true if some key
equal to the key exists within the
map, else return false.
boolean equals(Object o) It is used to compare the specified
Object with the Map.
int hashCode() It returns the hash code value for the
Map
boolean isEmpty() This method returns true if the map
is empty; returns false if it contains
at least one key.
Map Interface
import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
SortedMap - Interface
SortedMap - Interface
• The main characteristic of a SortedMap is that it orders the keys by
their natural ordering, or by a specified comparator. So consider using
a TreeMap when you want a map that satisfies the following criteria:
• null key or null value is not permitted.
• The keys are sorted either by natural ordering or by a specified
comparator
• The main difference between a SortedMap and a regular Map is that
the elements in a SortedMap are stored in a sorted order, whereas in
a Map the elements are stored in an arbitrary order.
.
SortedMap - Interface
• Since SortedMap is an interface, it can be used only with a class that
implements this interface.
• TreeMap is the class that implements the SortedMap interface. Now,
let’s see how to perform a few frequently used operations on the
TreeMap.
Syntax:
• SortedMap<Obj1, Obj2> set = new TreeMap<Obj1, Obj2> ();
Methods in Sorted Map
Comparator Interface
Java Comparator interface is used to order the objects of a user-
defined class.
Comparator is a generic interface that has this declaration:
interface Comparator<T>
Here, T specifies the type of objects being compared.
Methods of Java Comparator Interface (before
jdk 8.0)
Methods of Comparator (after jdk 8.)
Example of sorting the elements of List on the basis of age
and name.
public int getRollno() {
class Student {
return rollno;
int rollno;
}
String name;
int age; public void setRollno(int rollno) {
Student(int rollno,String name,int a this.rollno = rollno;
ge){
}
this.rollno=rollno;
this.name=name; public String getName() {
this.age=age; return name;
} }
Example of sorting the elements of List on the basis of age
and name.
/
import java.util.*; Sorting elements on the basis of na
public class TestSort1{ me
public static void main(String args[]) Comparator<Student> cm1=Comp
{ arator.comparing(Student::getNam
e);
ArrayList<Student> al=new ArrayList
<Student>(); Collections.sort(al,cm1);
System.out.println("Sorting by Na
al.add(new Student(101,"Vijay",23)) me");
;
for(Student st: al){
al.add(new Student(106,"Ajay",27));
System.out.println(st.rollno+" "+
st.name+" "+st.age);
al.add(new Student(105,"Jai",21)); }
Example of sorting the elements of List
on the basis of age and name.
//Sorting elements on the basis of age
Comparator<Student> cm2=Comparator
.comparing(Student::getAge);
Collections.sort(al,cm2);
System.out.println("Sorting by Age");
for(Student st: al){
System.out.println(st.rollno+" "+st.nam
e+" "+st.age);
}
}
}
Iterator Interface
The Java Iterator is an interface added in the Java Programming language
in the Java 1.2 Collection framework. It belongs to java.util package.
It is one of the Java Cursors that are practiced to traverse the objects of
the collection framework.
The Java Iterator is used to iterate the components of the collection
object one by one.
The Java Iterator is also known as the Universal cursor of Java as it is
appropriate for all the classes of the Collection framework.
The Java Iterator also supports the operations like READ and REMOVE.
The methods names of the Iterator class are very simple and easy to use
compared to the method names of Enumeration Iterator.
Java Iterator Methods
• The following figure perfectly displays the class diagram of the Java
Iterator interface. It contains a total of four methods that are:
hasNext()
next()
remove()
forEachRemaining()
Methods in Iterator Interface
boolean hasNext():
• The method does not accept any parameter. It returns true if there
are more elements left in the iteration.
• If there are no more elements left, then it will return false.
If there are no more elements left in the iteration, then there is no
need to call the next() method.
E next():
• It is similar to hasNext() method. It also does not accept any
parameter. It returns E, i.e., the next element in the traversal.
• If the iteration or collection of objects has no more elements left to
iterate, then it throws the NoSuchElementException.
Methods in Iterator Interface
void remove():
• This method also does not require any parameters.
• There is no return type of this method. The main function of this method
is to remove the last element returned by the iterator traversing t
void forEachRemaining(Consumer action): It is the only method of Java
Iterator that takes a parameter.
• It accepts action as a parameter. Action is nothing but that is to be
performed.
• There is no return type of the method. This method performs the
particularized operation on all of the left components of the collection
until all the components are consumed or the action throws an exception
JavaIteratorExample.java
import java.io.*; // Iterator to iterate the cityNames
import java.util.*; Iterator iterator = cityNames.iterator()
;
public class JavaIteratorExample {
public static void main(String[] args)
System.out.println("CityNames eleme
{ nts : ");
ArrayList<String> cityNames = new A
rrayList<String>(); while (iterator.hasNext())
cityNames.add("Delhi"); System.out.print(iterator.next() + " "
cityNames.add("Mumbai"); );
cityNames.add("Kolkata");
System.out.println();
cityNames.add("Chandigarh");
}
cityNames.add("Noida");
Collection Framework – Collection
Classes
Array List
• Java ArrayList class uses a dynamic array for storing
the elements. It is like an array, but there is no size
limit.
• User can add or remove elements anytime. So, it is
much more flexible than the traditional array.
• The ArrayList in Java can have the duplicate elements
also. It implements the List interface so we can use all
the methods of the List interface here. The ArrayList
maintains the insertion order internally.
• It inherits the AbstractList class and implements
List interface.
Characteristics of an ArrayList Class
• 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 the array works on an index basis.
• In ArrayList, manipulation is a little bit slower than the LinkedList in Java
because a lot of shifting needs to occur if any element is removed from the
array list.
• We can not create an array list of the primitive types, such as int, float, char,
etc. It is required to use the required wrapper class in such cases. For example:
• ArrayList<int> al = ArrayList<int>(); // does not work
• ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
Methods in Array List
Methods in Array List
Iterating Array List using Iterator
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
Linked List class
• 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.
Characteristics of Linked List class
• 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 occur.
• Java LinkedList class can be used as a list, stack or queue.
Methods in Linked List
Collection Class – Hashset
• HashSet stores the elements by using a
mechanism called hashing.
• HashSet contains unique elements
only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion
order. Here, elements are inserted on
the basis of their hashcode.
• HashSet is the best approach for
search operations.
Methods in Hashset
1.boolean contain(Object obj)
It is used to return true if this set contains the specified element.
2.Boolean isEmpty()
3.boolean remove(Object obj)
4.int size()
Example
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Java HashSet from another Collection
import java.util.*;
class HashSet4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");
list.add("Vijay");
list.add("Ajay");
1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector
Enumeraton Interface
HashTable
• Hashtable Class
• The Hashtable class is similar to HashMap. It also contains the data
into key/value pairs.
• It doesn't allow to enter any null key and value because it is
synchronized. Just like Vector, Hashtable also has the following four
constructors.
HashTable Methods
HashTable Methods
Hashtable Example
import java.util.*;
student.put(new Integer(104), "Ally");
class HashtableExample
Set dataset = student.entrySet();
{
Iterator iterate = dataset.iterator();
public static void main(String args[])
while(iterate.hasNext())
{
{
Hashtable<Integer,String> student = ne
w Hashtable<Integer, String>(); Map.Entry map=(Map.Entry)iterate.nex
t();
student.put(new Integer(101), "Emma")
; System.out.println(map.getKey()
+" "+map.getValue());
student.put(new Integer(102), "Adele");
}
student.put(new Integer(103), "Aria"); }
}
Properties – Legacy classes
Properties class methods
Example
prop_data.put("China", "CO2 Emissions
import java.util.*; and Renewable Energy.");
public class PropertiesExample prop_data.put("Sri Lanka", "Cinnamon.
{ ");
public static void main(String[] args) Set< ?
{ > set_data = prop_data.keySet();
Properties prop_data = new Properties(); for(Object obj: set_data)
prop_data.put("India", "Movies."); {
prop_data.put("United State", "Nobel Laur System.out.println(obj+" is famous fo
eates and Getting Killed by Lawnmowers."); r "+ prop_data.getProperty((String)obj));
prop_data.put("Pakistan", "Field Hockey."); }
}
}
Vector Class