Professional Documents
Culture Documents
Collections in Java Mod
Collections in Java Mod
Collections in Java Mod
Dr. Kuppusamy .P
Associate Professor / SCOPE
Collections
• A Collection represents a single unit of objects, i.e., a group.
• The Collection is a framework that provides an architecture to store and
manipulate the group of objects.
• Java Collections can achieve all the operations performing on a data such as
searching, sorting, insertion, manipulation, and deletion.
Two “root” interfaces of Java collection Framework
• Collection interface (java.util.Collection)
• Map interface (java.util.Map)
Framework:
• A framework is a set of classes and interfaces provide a ready-made architecture.
• Used to implement a new feature or a class, there is no need to define a
framework.
• Java Collection framework represents many interfaces (Set, List, Queue, Deque)
and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
Dr. Kuppusamy P
Collection Framework Hierarchy
LinkedHashSet
HashSet
Tree
Set
Iterable
Dr. Kuppusamy P
Collection Interface
• Interface contains methods and variables, but the methods only declared in an
interface (only method signature, no method definition).
• Collection interface extends the iterable interface and is implemented by all the
classes in the collection framework.
• This interface contains all the basic methods such as adding the data into the
collection, removing the data, clearing the data, etc.
• add(Object) -This method is used to add an object to the collection.
• addAll(Collection c) – It adds all the elements in the given collection to this
collection.
• clear() - This method removes all the elements from this collection.
• remove(Object o) It removes the given object from the collection. If
duplicate values exist, then removes the first occurrence of the object.
• All these methods are implemented by all the classes. Existence of these methods
in this interface ensures the methods are universal for all the collections i.e.,
collection interface builds a foundation on which the collection classes are
implemented.
Dr. Kuppusamy P
List Interface
• List Interface is a child interface of the collection interface.
• It is dedicated to the data of the list type in which user can store all the ordered
collection of the objects. This also allows duplicate data.
• The classes implements the List Interface are ArrayList, Vector, Stack,
LinkedList, etc.
• Since all the subclasses implement the list, user can instantiate a list object with
any of these classes.
Syntax:
• List < data_type > x = new ArrayList < data_type > ();
• List < data_type > y = new LinkedList < data_type > ();
• List < data_type > z = new Vector < data_type > ();
• List < data_type > z = new Stack < data_type > ();
• Create an ArrayList
• List <String> list1 = new ArrayList<String> ();
Dr. Kuppusamy P
ArrayList Class
• ArrayList provides us with dynamic arrays in Java.
• The size of an ArrayList is changes automatically i.e., grows or shrinks depends
on the object's addition and deletion.
• Java ArrayList allows us to randomly access the list.
• ArrayList can not be used for primitive types, like int, char, etc.
• User needs a wrapper class for such cases.
Dr. Kuppusamy P
ArrayList Example
import java.io.*;
import java.util.*;
class ArrayListEx {
public static void main(String[] args)
{
// Declaring the ArrayList
List<Integer> al = new ArrayList<Integer>();
// Appending new elements
for (int i = 100; i <= 105; i++)
al.add(i);
System.out.println(al);
// Remove element at index 3
al.remove(3);
System.out.println(al);
for (int i = 0; i < al.size(); i++)
System.out.print(al.get(i) + " ");
}
}
Dr. Kuppusamy P
Linked List Class
• LinkedList implements the Collection interface.
• LinkedList class is an implementation of the LinkedList data structure.
• It 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.
• It uses a doubly linked list internally to store the elements.
• It can store the duplicate elements.
• It maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.
Dr. Kuppusamy P
Linked List Class
import java.util.*;
public class LinkedListEx{
public static void main(String args[]){
List<String> al=new LinkedList<String>();
al.add(“Sai");
al.add(“Srinivas");
al.add(“Pavan");
al.add(“Pavani");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Dr. Kuppusamy P
Linked List Class
import java.io.*;
import java.util.*;
class LinkedListEx1 {
public static void main(String[] args)
{
List<Integer> x = new LinkedList<Integer>();
for (int i = 1; i <= 5; i++)
x.add(i);
System.out.println(x);
x.remove(3);
System.out.println(x);
}
}
Dr. Kuppusamy P
Vector Class
• Vector uses a dynamic array to store the data elements.
• It is identical to ArrayList in terms of implementation.
Difference between a vector and an ArrayList:
• Vector is synchronized and an ArrayList is non-synchronized.
import java.util.*;
public class VectorEx{
public static void main(String args[]){
List<String> v=new Vector<String>();
v.add("Sai");
v.add("Srinivas");
v.add("Pavan");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}} Dr. Kuppusamy P
Vector Class
import java.io.*;
import java.util.*;
class VectorEx1 {
public static void main(String[] args)
{
List<Integer> v = new Vector<Integer>();
for (int i = 101; i <= 105; i++)
v.add(i);
System.out.println(v);
v.remove(3);
System.out.println(v);
}
}
Dr. Kuppusamy P
Stack Class
• The stack is the subclass of Vector.
• Stack class implements the Stack data structure based on last-in-first-out.
• In addition to the push and pop operations, the class provides three more functions of
empty, search and peek.
import java.util.*;
public class StackEx{
public static void main(String args[]){
List<String> stack = new Stack<String>();
stack.push("Sai");
stack.push("Sree");
stack.push("Felix");
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); }
stack.pop();
itr=stack.iterator();
System.out.println("After Popping" );
while(itr.hasNext()){
System.out.println(itr.next());
} } } Dr. Kuppusamy P
Set Interface
• Set Interface extends the Collection interface.
• It represents the unordered set of elements .
• It cannot store the duplicate items.
• User can store at most one null value in Set.
• Set interface is implemented by HashSet, LinkedHashSet, and TreeSet.
Dr. Kuppusamy P
HashSet class
• HashSet class implements Set Interface.
• It represents the collection that uses a hash table as a storage.
• Hashing is used to store the unique elements in the HashSet.
import java.util.*;
public class Main{
public static void main(String args[]){
//CreatingHashSet
Set<String> set=new HashSet<String>();
set.add("Jai"); O/p:
set.add("Vineet"); Jai
set.add("Raj"); Vineet
set.add(“Raj"); Raj
//Traversingelements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Dr. Kuppusamy P
Map interface
• A map is a data structure that supports the key-value pair
mapping for the data.
• Map doesn’t support duplicate keys because the same key
cannot have multiple mappings.
• A map is useful if there is a data, user can perform
operations based on the key.
• Map interface is implemented by various classes such as
HashMap, TreeMap etc.
• Instantiate a map object with any of these classes due to all
the subclasses implement the map.
Ex.
Map <data-type> h1 = new HashMap <data-type> ();
Map< data-type > t1 = new TreeMap <data-type> ();
Dr. Kuppusamy P
HashMap class
• Map interface is frequently implemented by HashMap.
• It stores the data in (Key, Value) pairs.
• To access a value in a HashMap, user must know its key.
• HashMap uses a technique called Hashing which converts a large String to small
String that represents the same String.
• So, the indexing and search operations are faster. HashSet also uses HashMap
internally.
Map.Entry Interface
• Entry is the sub interface of Map. It can be accessed it by Map.Entry name.
• It returns a collection-view of the map, whose elements belong to this class.
• It provides methods to get key and value.
Dr. Kuppusamy P
HashMap class example
import java.util.*;
public class Main {
public static void main(String args[])
{
Map<Integer, String> h = new HashMap<Integer, String>();
h.put(1, "Hi");
h.put(2, "Welcome");
h.put(3, "To VIT-AP");
• hasNext() - It returns true if the iterator has more elements, otherwise returns false.
• next() - It returns the current element and moves the cursor pointer to the next
element.
Dr. Kuppusamy P
Iterator Example
import java.io.*; str = (String) i.next();
import java.util.*; if (str.equals("Sai")) {
class Main { i.remove();
public static void main(String[] args) System.out.println("\nThe element
{ is removed");
List<String> al = new ArrayList<String>(); break;
al.add("Sai"); }
al.add("Srinivas"); }
al.add("Pavan"); while (i.hasNext()){
Iterator<String> itr=al.iterator(); System.out.println(i.next());
while(itr.hasNext()){
System.out.println(itr.next()); }
// deletes last element }}
}
Iterator <String> i = al.iterator();
String str = "";
while (i.hasNext()) {
Dr. Kuppusamy P
Iterable Interface
• The Iterable interface is the root interface for all the collection classes.
• The Collection interface extends the Iterable interface.
• To use for loop to elements, the class must implement the iterable interface.
• for-each loop uses iterable interface internally for iterating over objects of the
implemented class.
• Iterables does not have a current state, rather it delivers an iterator method.
• It contains only one abstract method is the iterator() that internally called by
iterable interface.
Dr. Kuppusamy P
Iterable Interface Example
import java.util.Iterator;
class Simple implements Iterable<T> {
//lines of code for the problem
Dr. Kuppusamy P
Iterable Interface Example
// moves the cursor/iterator to next element
public T next() {
}
Dr. Kuppusamy P
for each loop using Iterable Interface internally
import java.util.*;
public class Main
{
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
Dr. Kuppusamy P
Comparator Interface
• A comparator interface is used to order (ascending) the objects of user-defined
classes.
• A comparator object is capable of comparing two objects of two different classes.
Two methods in Comparator:
compare()
equal()
Example:
int compare(T object1, T object2)
• The compare method returns
• a negative number if object1 is less than object2,
• zero if object1 and object2 are equal, and
• a positive number if object1 is greater than the object2.
Dr. Kuppusamy P
Comparator Interface
import java.util.*;
class Student {
int rollno;
String name;
public Student(int rollno, String name)
{
this.rollno = rollno;
this.name = name;
}
Dr. Kuppusamy P
Comparator Interface
class Sortbyroll implements Comparator<Student> {
// ascending order of roll number
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}
Dr. Kuppusamy P
Comparator Interface
class Main {
public static void main(String[] args)
{
List<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "bbbb"));
ar.add(new Student(131, "aaaa"));
ar.add(new Student(121, “cccc"));
Output:
Sorted by rollno
111 bbbb
121 cccc
131 aaaa
Sorted by name
131 aaaa
111 bbbb
121 cccc
Dr. Kuppusamy P
References
Dr. Kuppusamy P