You are on page 1of 27

Collection Framework

Definition of collection
♦ A collection — sometimes called a container — is simply an object that
groups multiple elements into a single unit.

♦ Collections are used to store, retrieve, manipulate, and communicate


aggregate data.

♦ They typically represent data items that form a natural group,


e.g.
– poker hand (a collection of cards),
– a mail folder (a collection of letters),
– or a telephone directory (a mapping from names to phone numbers).
What is a Java Collection Framework?
A Java collection framework provides an architecture to store and manipulate a group of
objects. A Java collection framework includes the following:

♦ Interfaces
♦ Classes
♦ Algorithm
Collections-related Interface hierarchy

Collection Map Iterator

List Set SortedMap ListIterator

SortedSet

• The Collection inteface stores groups of Objects, with duplicates allowed


• The Set interface extends Collection but forbids duplicates
• The List interface extends Collection, allows duplicates, and introduces positional indexing.
• Map is a separate hierarchy
Hierarchy of Collection Framework
Java Collections – List
A List is an ordered Collection (sometimes called a sequence). Lists may
contain duplicate elements. Elements can be inserted or accessed by their
position in the list, using a zero-based index.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :

List <data-type> list1= new ArrayList();


List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the elements from
the list.
Java Collections – List - ArrayList
What is ArrayList?

Why ArrayList is better than Array?

How to create an ArrayList class object?


ArrayList<String> alist=new ArrayList<String>();
Methods of ArrayList class
1) add( Object o): This method adds an object o to the arraylist.
e.g. :- obj.add("hello");
2) add(int index, Object o): It adds the object o to the array list at the given index.
e.g. :- obj.add(2, "bye");
3) remove(Object o): Removes the object o from the ArrayList.
e.g. :- obj.remove("java");
4) remove(int index): Removes element from a given index.
e.g. :- obj.remove(3);
5) set(int index, Object o): Used for updating an element. It replaces the element present
at the specified index with the object o.
e.g. :- obj.set(2, "Tom");
Methods of ArrayList class
6) int indexOf(Object o): Gives the index of the object o. If the element is not found in the
list then this method returns the value -1.
e.g. :- int pos = obj.indexOf("Tom");
7) Object get(int index): It returns the object of list which is present at the specified index.
e.g. :- String str= obj.get(2);
8) int size(): It gives the size of the ArrayList – Number of elements of the list.
e.g. :- int numberofitems = obj.size();
9) boolean contains(Object o): It checks whether the given object o is present in the array
list if its there then it returns true else it returns false.
e.g. :- obj.contains("Steve");
10) clear(): It is used for removing all the elements of the array list in one go. The below
code will remove all the elements of ArrayList whose object is obj.
e.g. :- obj.clear();
Java Collections – List - ArrayList Example
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
Output ????
list.add("Ravi");//Adding object in arraylist
list.add("Vijay"); Ravi
list.add("Ravi");
list.add("Ajay"); Vijay
//Traversing list through Iterator Ravi
Iterator itr=list.iterator();
while(itr.hasNext()){ Ajay
System.out.println(itr.next()); }
list.remove(“Vijay”);
Ravi
Iterator itr1=list.iterator(); Ravi
while(itr1.hasNext()){
System.out.println(itr1.next());
Ajay
} [Ravi,Ravi,Ajay]
System.out.println(list);
}
}
Java Collections – List - Vector
What is Vector?
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of Collection
framework.

How to create an Vector class object?(3 ways)


1. Vector vec = new Vector();
//default capacity = 10 if add elemnt at 11th position capacity =20 double the
capacity
2. Vector object= new Vector(int initialCapacity)
e.g. :- Vector vec = new Vector(3);//will create a Vector of initial capacity of 3.
3. Vector object= new vector(int initialcapacity, capacityIncrement)
e.g. :- Vector vec= new Vector(4, 6) // Initial capacity =4 and capacityIncrement =6. It
means upon insertion of 5th element the size would be 10 (4+6) and on 11th insertion it
would be 16(10+6).
Methods of Vector class
1. void addElement(Object element): It inserts the element at the end of the Vector.
2. int capacity(): This method returns the current capacity of the vector.
3. int size(): It returns the current size of the vector.
4. void setSize(int size): It changes the existing size with the specified size.
5. boolean contains(Object element): This method checks whether the specified element is present in the
Vector. If the element is been found it returns true else false.
6. boolean containsAll(Collection c): It returns true if all the elements of collection c are present in the
Vector.
7. Object elementAt(int index): It returns the element present at the specified location in Vector.
8. Object firstElement(): It is used for getting the first element of the vector.
9. Object lastElement(): Returns the last element of the array.
10. Object get(int index): Returns the element at the specified index.
11. boolean isEmpty(): This method returns true if Vector doesn’t have any element.
12. boolean removeElement(Object element): Removes the specifed element from vector.
13. boolean removeAll(Collection c): Removes all those elements from vector which are present in the
Collection c.
14. void setElementAt(Object element, int index): It updates the element of specifed index with the given
element.
Java Collections – List - Vector Example
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
Vector<String> vec = new Vector<String>(2);
Output ????
vec.addElement("Apple");//adding elements
vec.addElement("Orange"); Size is: 4
vec.addElement("Mango"); Default capacity increment is: 4
vec.addElement("Fig");
System.out.println("Size is: "+vec.size()); Size after addition: 7
System.out.println("Default capacity increment is: "+ vec.capacity()); Capacity after increment is: 8
vec.addElement("fruit1");
vec.addElement("fruit2");
vec.addElement("fruit3");
System.out.println("Size after addition: "+vec.size());
Elements are:
System.out.println("Capacity after increment is: "+vec.capacity()); AppleOrangeMangoFigfruit1fru
Iterator it = vec.iterator();
System.out.println("Vector elements are:"); it2fruit3
while(it.hasNext()){
System.out.print(it.next());}
}
Java Collections – List - LinkedList
What is LinkedList?
LinkedList is a linear data structure. However LinkedList elements are not stored in
contiguous locations like arrays, they are linked with each other using pointers. Each
element of the LinkedList has the reference(address/pointer) to the next element of the
LinkedList. It maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.

How to create an LinkedList class object?


LinkedList<String> al=new LinkedList<String>();

Why do we need a Linked List?


• Linked list allows dynamic memory allocation.
• Linked list elements don’t need contiguous memory locations.
• Insert and delete operations in the Linked list are not performance wise expensive
because adding and deleting an element from the linked list does’t require element
shifting, only the pointer of the previous and the next node requires change.
Methods of LinkedListclass
1. boolean add(Object item): It adds the item at the end of the list.
2. void add(int index, Object item): It adds an item at the given index of the the list.
3. boolean addAll(Collection c): It adds all the elements of the specified collection c to the list.
4. boolean addAll(int index, Collection c): It adds all the elements of collection c to the list starting from a
give index in the list.
5. void addFirst(Object item): It adds the item (or element) at the first position in the list.
6. void addLast(Object item): It inserts the specified item at the end of the list .
7. void clear(): It removes all the elements of a list.
8. Object clone(): It returns the copy of the list.
9. boolean contains(Object item): It checks whether the given item is present in the list or not. If the item is
present then it returns true else false.
10. Object get(int index): It returns the item of the specified index from the list.
11. Object getLast(): It fetches the last item from the list.
12. Object getFirst(): It fetches the first item from the list.
13. int indexOf(Object item): It returns the index of the specified item.
Methods of LinkedListclass

14. int lastIndexOf(Object item): It returns the index of last occurrence of the specified element.
15. Object poll(): It returns and removes the first item of the list.
16. Object pollFirst(): same as poll() method. Removes the first item of the list.
17. Object pollLast(): It returns and removes the last element of the list.
18. Object remove(): It removes the first element of the list.
19. Object remove(int index): It removes the item from the list which is present at the specified index.
20. Object remove(Object obj): It removes the specified object from the list.
21. Object removeFirst(): It removes the first item from the list.
22. Object removeLast(): It removes the last item of the list.
23. Object removeFirstOccurrence(Object item): It removes the first occurrence of the specified item.
24. Object removeLastOccurrence(Object item): It removes the last occurrence of the given element.
25. Object set(int index, Object item): It updates the item of specified index with the give value.
26. int size(): It returns the number of elements of the list.
Java Collections – List - LinkedListExample
import java.util.*;
public class LinkedListExample {
public static void main(String args[]) {
LinkedList<String> linkedlist = new LinkedList<String>();
Output ????
linkedlist.add("Item1");//adding elements Linked List Content: [Item1, Item5, Item3,
linkedlist.add("Item5"); Item6, Item2]
linkedlist.add("Item3");
linkedlist.add("Item6"); LinkedList Content after addition: [First Item,
linkedlist.add("Item2"); Item1, Item5, Item3, Item6, Item2, Last Item]
System.out.println("Linked List Content: " +linkedlist);
linkedlist.addFirst("First Item");//add first elements LinkedList after deletion of first and last
linkedlist.addLast("Last Item");//add last element element: [Item1, Item5, Item3, Item6, Item2]
System.out.println("LinkedList Content after addition: " +linkedlist);
linkedlist.removeFirst(); Final Content: [Newly added item, Item1,
linkedlist.removeLast(); Item3, Item6, Item2]
System.out.println("LinkedList after deletion of first and last element: "
+linkedlist);
linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: " +linkedlist);
ArrayList vs Vector
ArrayList Vector

Synchronization ArrayList is non-synchronized which Vector is synchronized. This means if


means multiple threads can work on one thread is working on Vector, no
ArrayList at the same time. other thread can get a hold of it.

Resize ArrayList grow by half of its size when Vector doubles the size of itself by
resized by default. default when grows.

Performance ArrayList gives better performance as Vector operations gives poor


it is non-synchronized performance as they are thread-safe
ArrayList vs LinkedList
ArrayList LinkedList

Search ArrayList search operation is pretty


fast compared to the LinkedList

Deletion LinkedList element deletion is faster


compared to ArrayList.

Performance ArrayList gives O(n) in worst case. LinkedList add method gives O(1)
performance

Memory Overhead ArrayList maintains indexes and LinkedList maintains element data and
element data two pointers for neighbor nodes hence
the memory consumption is high in
LinkedList comparatively.
Java Collections – List - Stack
The Java Stack interface represents a classical stack data structure, where elements can be pushed to last-in-first-out
(LIFO) stack of objects. In Stack we push an element to the top of the stack, and popped off from the top of the stack
again later.

Methods of Stack Class


Object push(Object element) : Pushes an element on the top of the stack.
Object pop() : Removes and returns the top element of the stack. An ‘EmptyStackException’ exception
is thrown if we call pop() when the invoking stack is empty.
Object peek() : Returns the element on the top of the stack, but does not remove it.
boolean empty() : It returns true if nothing is on the top of the stack. Else, returns false.
int search(Object element) : It determines whether an object exists in the stack. If the element is
found, it returns the position of the element from the top of the stack. Else, it returns -1.
import java.io.*;
import java.util.*;

class Test
{ static void stack_push(Stack<Integer> stack) // Pushing element on the top of the stack
{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}}
static void stack_pop(Stack<Integer> stack) // Popping element from the top of the stack
{ Output ????
System.out.println("Pop :");
for(int i = 0; i < 5; i++)
{ Pop :
Integer y = (Integer) stack.pop();
System.out.println(y);
4
}} 3
static void stack_peek(Stack<Integer> stack) // Displaying element on the top of the stack
{ 2
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top : " + element); }
1
static void stack_search(Stack<Integer> stack, int element) // Searching element in the stack { 0
Integer pos = (Integer) stack.search(element);
Element on stack top : 4
if(pos == -1) Element is found at position 3
System.out.println("Element not found");
else Element not found
System.out.println("Element is found at position " + pos); }
public static void main (String[] args)
{
Stack<Integer> stack = new Stack<Integer>();
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6); } }
Hierarchy of Map
Java Map Interface
❖ 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. A Map contains unique keys.

❖ A Map is useful if you have to search, update or delete elements on the basis of a key.

❖ A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or
value.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't
maintain any order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits
HashMap class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It
maintains ascending order.
Java Map -HashMap-Example
import java.util.*;
class MapExample2{
public static void main(String args[]){
Output ????
Map<Integer,String> map=new HashMap<Integer,String>();
//Adding elements to map
map.put(100,"Amit"); Map Elements
map.put(101,"Vijay"); {100=Amit, 101=Vijay, 102=Rahul}
map.put(102,"Rahul"); Map Elements
System.out.println(" Map Elements"); {100=Amit, 101=Vijay}
System.out.print("\t" + map);
map.remove(102); //removing element
System.out.println(" Map Elements");
System.out.print("\t" + map);
}
}
Java Set Interface

• Set is an interface which extends


Collection. It is an unordered collection
of objects in which duplicate values
cannot be stored.
• Basically, Set is implemented by
HashSet, LinkedHashSet or TreeSet
(sorted representation).
• Set has various methods to add,
remove clear, size, etc to enhance the
usage of this interface.
Java Map -HashSet-Example
// Java code for adding elements in Set
import java.util.*;
public class Set_example
{ public static void main(String[] args)
Output ????
{ // Set deonstration using HashSet
Set<String> hash_Set = new HashSet<String>(); Set output without the
hash_Set.add("Geeks"); duplicates[Geeks, Example,
hash_Set.add("For"); For, Set]
hash_Set.add("Geeks");
Sorted Set after passing into
hash_Set.add("Example");
hash_Set.add("Set"); TreeSet[Example, For, Geeks,
System.out.print("Set output without the duplicates"); Set]

System.out.println(hash_Set);

// Set deonstration using TreeSet


System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
}}
Thank You

You might also like