1 of 35

Collection Frame Work In Java

2 of 35

INTRODUCTION

  • To store group of elements or group of similar type of objects we use “Arrays”.

Disadvantages:

  • Fixed size
  • Stores only homogeneous elements.
  • Difficult to add an object at middle of the list.

To overcome this problem java introduces Collection Framework.

3 of 35

Collection FRAMEWORK

  • Collection framework is a class library to handle group of objects and it is implemented in java.util package.
  • 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.
  • Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), or a telephone directory (a mapping of names to phone numbers).

4 of 35

All Collections Frameworks Contain

  • Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements. 
  • Set — a collection that cannot contain duplicate elements.
  • List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position).

5 of 35

  • Queue — a collection used to hold multiple elements prior to processing. a Queue provides additional insertion, extraction, and inspection operations. Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements' natural ordering.
  • SortedSet — a Set that maintains its elements in ascending order.  

6 of 35

Methods To Retrieve The Elements From The Collection Object Are

  • ForEach Group
  • Enumeration Interface
  • Iterator Interface
  • ListIterator

7 of 35

ForEach Group

  • To display the values in an array and collection , instead of FOR loop, we can use ForEach Group.
  • This is also called as enhanced for loop and is useful for scanning array elements.

Ex: int a[]={1,2,3,4,5};

For Loop

ForEach Group

Syntax:

For(intialization;condition;increment/decrement)

{

}

Syntax:

For(data_type variable:array_name)

{

}

Ex:

For(int i=0;i<a.lenth;i++)

{

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

}

Ex:

For(int x:a)

{

System.out.println(x);

}

8 of 35

Enumeration Interface

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.

boolean hasMoreElements( )

It returns true, if enumaration contains the elements.

Object nextElement( )

It returns the next element available in the enumaration.

Note: this is applicable only legacy classes(Vector).

9 of 35

Ex:

import java.util.Vector;

import java.util.Enumeration;

public class EnumerationTester {

public static void main(String args[]) {

Enumeration days;

Vector dayNames = new Vector();

dayNames.add("Sunday");

dayNames.add("Monday");

dayNames.add("Tuesday");

dayNames.add("Wednesday");

dayNames.add("Thursday");

dayNames.add("Friday");

dayNames.add("Saturday");

days = dayNames.elements();

while (days.hasMoreElements())

{

System.out.println(days.nextElement());

} } }

10 of 35

Iterator INTERFACE

  • Generally, while iterating a loop, we can only perform read-only operation, but with this interface we can do removal too.
  • Using iterator(), we can get iterator object and with this interface we can only move in forward direction only.

Iterator hasNext()-> returns true if the iteration has more elements remaining in the collection.

Iterator next()->This method returns the next element in the iteration.

Iterator remove()-> it removes the last element.

11 of 35

Ex:

import java.io.*;

import java.util.*;

 class Test {

    public static void main(String[] args)

{

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

 list.add("A");

list.add("B");

list.add("C");

list.add("D");

System.out.println(list);

Iterator<String> iterator = list.iterator();

 while(iterator.hasNext())

{

       String value = iterator.next();

         System.out.println( value );

         if(value.equals("B")) {

        iterator.remove();

    }

System.out.println(list);

} }

Output:

[A, B, C, D]

A

B

C

D

[A, C, D]

12 of 35

ListIterator

  • ListIterator extends Iterator interface.
  • ListIterator is applicable only for List implemented classes.
  • Unlike Iterator, ListIterator supports all CRUD operations (CREATE, READ, UPDATE and DELETE) over a list of elements.
  • Unlike Iterator, ListIterator is bi-directional. It supports both forward direction and backward direction iterations.
  • It has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

13 of 35

Methods In ListIterator Interface Are

Note: We can obtain the reference to list iterator for any given list using list.listIterator() method call.  

ListIterator<T> listIterator = list.listIterator();

Method

Description

hasNext()

Checks if there is a next element.

next()

Returns the next element in the list.

hasPrevious()

Checks if there is a previous element.

previous()

Returns the previous element.

remove()

Removes the last element returned by next() or previous().

add(Object o)

Adds a new element to the list.

14 of 35

Ex

import java.io.*;

import java.util.*;

 class Test {

    public static void main(String[] args)

{

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

 list.add("A");

list.add("B");

list.add("C");

list.add("D");

list.add("E");

list.add("F");

ListIterator<String> listIterator = list.listIterator();

 System.out.println("Forward iteration");

 while(listIterator.hasNext()) {

    System.out.print(listIterator.next() + ",");

}

 System.out.println("Backward iteration");

 

while(listIterator.hasPrevious()) {

    System.out.print(listIterator.previous() + ",");

}

 System.out.println("Iteration from specified position");

listIterator = list.listIterator(2);

 while(listIterator.hasNext()) {

    System.out.print(listIterator.next() + ",");

} } }

Output:

Forward iteration

A,B,C,D,E,F,

 

Backward iteration

F,E,D,C,B,A,

 

Iteration from specified position

C,D,E,F,

15 of 35

16 of 35

List Interface

17 of 35

Vector

  • Vector is part of the java.util package.
  • It implements the List interface — similar to ArrayList.
  • It stores elements in a dynamic array that grows automatically. It is synchronized (thread-safe), meaning only one thread can modify it at a time. It is considered a legacy class (older class before Java Collections Framework).

Method

Description

add(E e)

Adds an element at the end of the vector.

add(int index, E e)

Inserts an element at a specific position.

remove(int index)

Removes element at the given index.

get(int index)

Returns the element at the given index.

size()

Returns number of elements in the vector.

capacity()

Returns the current capacity of the vector.

18 of 35

Ex:

import java.util.*;

public class VectorExample

{

public static void main(String[] args)

{

Vector<String> v = new Vector<>();

v.add("Red");

v.add("Green");

v.add("Blue");

System.out.println("Vector elements: " + v);

System.out.println("Size: " + v.size());

System.out.println("Capacity: " + v.capacity());

}

}

Output:

Vector elements:

[Red, Green, Blue]

Size: 3Capacity: 10

19 of 35

ArrayList

  • Arraylist class implements List interface and it is based on an Array data structure.
  • ArrayList is a resizable-array implementation of the List interface.
  • It implements all optional list operations, and permits all elements, including null.
  • Allows duplicate elements and maintains insertion order.
  • Provides random access using index (like arrays).
  • Grows automatically when more elements are added.

20 of 35

Methods in ArrayList are:

Method

Description

add(E e)

Adds element at the end of list.

add(int index, E e)

Inserts element at specified position (middle possible).

get(int index)

Returns element at specified index.

set(int index, E e)

Replaces element at the given position.

remove(int index)

Removes element at specified position.

size()

Returns total number of elements.

clear()

Removes all elements.

Syntax: ArrayList<String> alist=new ArrayList<String>();

21 of 35

Ex :

import java.util.*;

class JavaExample

{

public static void main(String args[]){

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

alist.add("Steve");

alist.add("Tim");

alist.add("Lucy");

alist.add("Pat");

alist.add("Angela");

alist.add("Tom");

System.out.println(alist);

alist.remove("Steve");

alist.remove("Angela");

System.out.println(alist);

alist.remove(2);

System.out.println(alist);

}

}

Output:

[Steve, Tim, Lucy, Pat, Angela, Tom]

[Tim, Lucy, Pat, Tom]

[Tim, Lucy, Tom]

22 of 35

LinkedList

  • LinkedList is a class in the java.util package.
  • It implements both List and Deque interfaces.
  • It stores elements in a doubly linked list structure (each node links to the next and previous one).
  • It allows duplicate elements and maintains insertion order.
  • It is faster for insertion and deletion than ArrayList.

23 of 35

Methods in LinkedList are:

Syntax: LinkedList<String> alist=new LinkedList<String>();

Method

Description

add(E e)

Adds an element at the end.

addFirst(E e)

Adds an element at the beginning.

addLast(E e)

Adds an element at the end (same as add).

getFirst()

Returns the first element.

getLast()

Returns the last element.

removeFirst()

Removes the first element.

removeLast()

Removes the last element.

size()

Returns the number of elements.

clear()

Removes all elements.

24 of 35

Ex :

import java.util.*;

public class LinkedListExample {

public static void main(String[] args) {

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

animals.add("Dog"); animals.add("Cat"); animals.add("Cow"); animals.addFirst("Elephant"); animals.addLast("Tiger"); System.out.println("LinkedList: " + animals);

System.out.println("First Element: " + animals.getFirst()); System.out.println("Last Element: " + animals.getLast()); animals.removeFirst(); animals.removeLast();

System.out.println("After removing first and last: " + animals);

}

}

Output:

LinkedList:

[Elephant, Dog, Cat, Cow, Tiger]

First Element: Elephant

Last Element: Tiger

After removing first and last:

[Dog, Cat, Cow]

25 of 35

Stack

  • Stack<E> is a class in java.util.
  • It follows the LIFO (Last In, First Out) principle — last element pushed is the first one popped.
  • Internally it extends the Vector class (so it inherits behaviours from Vector).
  • It is considered a legacy class; for new code, ArrayDeque<E> or LinkedList<E> are often recommended.

26 of 35

Methods in Stack are:

Method

Description

push(E item)

Adds (pushes) an item onto the top of the stack.

E pop()

Removes and returns the top item of the stack.

E peek()

Looks at (but does not remove) the top item of the stack.

boolean empty()

Checks if the stack is empty.

int search(Object o)

Searches for an item and returns its 1-based position from the top if found, otherwise returns –1.

27 of 35

Ex:

import java.util.Stack;

public class StackExample {

public static void main(String[] args)

{

Stack<String> stack = new Stack<>();

stack.push("Apple");

stack.push("Banana");

stack.push("Cherry");

System.out.println("Top element (peek): " + stack.peek()); System.out.println("Popped: " + stack.pop());

System.out.println("Is stack empty? " + stack.empty());

stack.pop();

stack.pop();

System.out.println("Is stack empty after popping all? " + stack.empty());

}

}

Top element (peek): Cherry

Popped: Cherry

Is stack empty? False

Is stack empty after popping all? true

28 of 35

QueueList

  • The Queue is an interface in the java.util package.
  • It follows the FIFO principle — First In, First Out.
  • Elements are added at the rear (tail) and removed from the front (head).

Common implementations:

LinkedList (most commonly used)

PriorityQueue (orders elements by priority)

29 of 35

Methods in QueueList are:

Method

Description

add(E e)

Inserts the element into the queue; throws exception if full.

offer(E e)

Inserts element; returns false if full (no exception).

remove()

Removes and returns the head of the queue; throws exception if empty.

poll()

Removes and returns head; returns null if empty.

element()

Returns (but does not remove) the head element; throws exception if empty.

peek()

Returns (but does not remove) head; returns null if empty.

30 of 35

Ex:

import java.util.*;

public class QueueExample {

public static void main(String[] args)

{

Queue<String> queue = new LinkedList<>();

queue.add("Task1");

queue.add("Task2");

queue.add("Task3");

System.out.println("Initial Queue: " + queue);

System.out.println("Head element (peek): " + queue.peek());

System.out.println("Removed: " + queue.remove()); System.out.println("Queue after removal: " + queue);

queue.offer("Task4");

System.out.println("After offer: " + queue);

queue.poll();

System.out.println("After poll: " + queue);

}}

Initial Queue: [Task1, Task2, Task3]

Head element (peek): Task1

Removed: Task1

Queue after removal: [Task2, Task3]

After offer: [Task2, Task3, Task4]

After poll: [Task3, Task4]

31 of 35

  • HashMap is a class in the java.util package.
  • It stores data as key–value pairs (just like a dictionary).
  • Each key is unique, but values can be duplicated.
  • It uses hashing to store and retrieve elements efficiently.
  • Null keys and values are allowed (but only one null key).
  • It does not maintain insertion order — elements are unordered.

Hashmap

32 of 35

Method

Description

put(K key, V value)

Inserts or updates a key–value pair.

get(Object key)

Returns the value for the given key.

remove(Object key)

Removes the entry for the given key.

containsKey(Object key)

Checks if the key exists.

containsValue(Object value)

Checks if a value exists.

keySet()

Returns a set of all keys.

values()

Returns a collection of all values.

entrySet()

Returns a set of key–value pairs (Map.Entry objects).

size()

Returns the number of key–value pairs.

clear()

Removes all entries.

Methods in Hashmap are:

33 of 35

Ex:

import java.util.*;

public class HashMapExample {

public static void main(String[] args)

{

HashMap<Integer, String> map = new HashMap<>();

map.put(1, "Java");

map.put(2, "Python");

map.put(3, "C++");

System.out.println("HashMap: " + map);

System.out.println("Value for key 2: " + map.get(2));

map.remove(3);

System.out.println("Contains key 1? " + map.containsKey(1)); System.out.println("Contains value 'C++'? " + map.containsValue("C++"));

System.out.println("Keys: " + map.keySet()); System.out.println("Values: " + map.values());

}}

HashMap: {1=Java, 2=Python, 3=C++}

Value for key 2: Python

Contains key 1? True

Contains value 'C++'? False

Keys: [1, 2]

Values: [Java, Python]

34 of 35

String Tokenizer

  • StringTokenizer (in java.util package) is used to split a string into smaller parts called tokens.
  • Tokens are separated by delimiters (like space, comma, etc.).
  • Often used for parsing CSV data or splitting sentences.

Method

Description

hasMoreTokens()

Checks if more tokens are available.

nextToken()

Returns the next token (word).

countTokens()

Returns how many tokens are left.

35 of 35

Ex:

import java.util.*;

public class StringTokenizerExample {

public static void main(String[] args) {

String str = "Java,Python,C++,C";

StringTokenizer st = new StringTokenizer(str, ",");

System.out.println("Tokens are:");

while (st.hasMoreTokens())

{

System.out.println(st.nextToken());

}

}}

Tokens are:

Java

Python

C++

C