You are on page 1of 15

1

Collections in Java
Java collections refer to a collection of individual objects that are represented as a single unit.
You can perform all operations such as searching, sorting, insertion, manipulation, deletion,
etc., on Java collections just like you do it on data.

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
Let’s learn about them in detail:
Interfaces: Interface in Java refers to the abstract data types. They allow Java
collections to be manipulated independently from the details of their representation. Also, they
form a hierarchy in object-oriented programming languages.
Classes: Classes in Java are the implementation of the collection interface. It basically
refers to the data structures that are used again and again.
Algorithm: Algorithm refers to the methods which are used to perform operations such
as searching and sorting, on objects that implement collection interfaces. Algorithms are
polymorphic in nature as the same method can be used to take many forms or you can say
perform different implementations of the Java collection interface.

Why use Java collection?


There are several benefits of using Java collections such as:
 Reducing the effort required to write the code by providing useful data structures and
algorithms
 Java collections provide high-performance and high-quality data structures and
algorithms thereby increasing the speed and quality.
 Unrelated APIs can pass collection interfaces back and forth.
 Decreases extra effort required to learn, use, and design new API’s
 Supports reusability of standard data structures and algorithms

Java Collection Framework Hierarchy


As we have learned Java collection framework includes interfaces and classes. Now,
let us see the Java collections framework hierarchy.
Java Collections: Interface
Iterator interface: Iterator is an interface that iterates the elements. It is used to traverse the
list and modify the elements. Iterator interface has three methods which are mentioned below:

 public boolean hasNext() – This method returns true if the iterator has more elements.
 public object next() – It returns the element and moves the cursor pointer to the next
element.
 public void remove() – This method removes the last elements returned by the iterator.

CSIT Dept. GITA Autonomous College Prof. Debasish Das


2

Here are three components that extend the collection interface i.e List, Queue and Sets.
Let’s learn about them in detail:

Java collections: List


A List is an ordered Collection of elements which may contain duplicates. It is an interface
that extends the Collection interface. Lists are further classified into the following:
1. ArrayList
2. LinkedList
3. Vectors
Let’s go into detail on each one of them:
Array list: ArrayList is the implementation of List Interface where the elements can be
dynamically added or removed from the list. Also, the size of the list is increased dynamically
if the elements are added more than the initial size.

CSIT Dept. GITA Autonomous College Prof. Debasish Das


3

Method Description
boolean add (Collection c) Appends the specified element to the end of a list.
void add (int index, Inserts the specified element at the specified position.
Object element)
void clear() Removes all the elements from this list.
int lastIndexOf (Object o) Return the index in this list of the last occurrence of the specified
element, or -1 if the list does not contain this element.
Object clone() Return a shallow copy of an ArrayList.
Object[ ] toArray() Returns an array containing all the elements in the list.
void trimToSize() Trims the capacity of this ArrayList instance to be the list’s
current size

Method Description
public boolean hasNext() It returns true if the iterator has more elements otherwise it returns
false.

public Object next() It returns the element and moves the cursor pointer to the next
element.

public void remove() It removes the last elements returned by the iterator. It is less used.

Syntax:
ArrayList object = new ArrayList ();
Some of the methods in array list are listed below:
Example:
import java.util.*;
public class list1
{
public static void main(String args[])
{
ArrayList a1 = new ArrayList();
System.out.println("size of ArrayList "+a1.size());

a1.add(1); // add method element to the ArrayList


a1.add("C");
a1.add(12);
System.out.println("ArrayList "+a1);
a1.add(1,"c++"); // add an item in a specfic index
// display all elements inside the arraylist
System.out.println("After add ArrayList "+a1);
int i = a1.lastIndexOf(12); // return index of a value
System.out.println("Index value " +i);
System.out.println(" value " +a1.get(1));// give index value
and return value

Iterator itr =a1.iterator();


while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

CSIT Dept. GITA Autonomous College Prof. Debasish Das


4

Linked List: Linked List is a sequence of links which contains items. Each link contains a
connection to another link.

Syntax: Linkedlist object = new Linkedlist();

Java Linked List class uses two types of Linked list to store the elements:
 Singly Linked List
 Doubly Linked List

Singly Linked List: In a singly Linked list each node in this list stores the data of the node and a pointer
or reference to the next node in the list. Refer to the below image to get a better understanding of single
Linked list.

Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and another to
previous node. You can refer to the below image to get a better understanding of doubly linked list.

Method Description
addFirst() Adds an item to the beginning of the list.
addLast() Add an item to the end of the list
removeFirst() Remove an item from the beginning of the list.
removeLast() Remove an item from the end of the list
getFirst() Get the item at the beginning of the list
getLast() Get the item at the end of the list

public class linklist


{
public static void main(String[] args)
{
LinkedList cars = new LinkedList();
cars.add("Volvo");
cars.add("BMW");

CSIT Dept. GITA Autonomous College Prof. Debasish Das


5

cars.add("Ford");
cars.add("Mazda");
//System.out.println(cars);
//addFirst() Adds an item to the beginning of the list.
cars.addFirst("Mazda");
//addLast() Add an item to the end of the list
cars.addLast("Maruti");
//System.out.println(cars);
// Use removeFirst() remove the first item from the list
System.out.println("value "+cars.removeFirst());

/* Iterator itr =cars.iterator();


while(itr.hasNext())
{
System.out.println(itr.next());
}*/

// Use getFirst() to display the first item in the list


System.out.println("1st element "+cars.getFirst());
System.out.println(cars);
}
}
Example :2
import java.util.*;

public class linklist1


{
public static void main(String[] args)
{
LinkedList cars = new LinkedList();
//LinkedList<Integer> cars = new <Integer>LinkedList();
cars.add(1);
cars.add(22);
cars.add("-500");
cars.add(300);
System.out.println(cars);
}
}
Vectors: Vectors are similar to arrays, where the elements of the vector object can be accessed
via an index into the vector. Vector implements a dynamic array. Also, the vector is not limited
to a specific size, it can shrink or grow automatically whenever required. It is similar to
ArrayList, but with two differences:

 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.

ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of current Vector increments 100% means doubles the
array size if the number of elements array size if the total number of elements exceeds
exceeds from its capacity. than its capacity.

CSIT Dept. GITA Autonomous College Prof. Debasish Das


6

3) ArrayList is not a legacy class. It is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized, i.e., in a


synchronized. multithreading environment, it holds the other
threads in runnable or non-runnable state until
current thread releases the lock of the object.

5) ArrayList uses the Iterator interface A Vector can use the Iterator interface
to traverse the elements. or Enumeration interface to traverse the
elements.

work on ArrayList at
Note : ArrayList is non synchronized because if ArrayList is synchronized then only one thread can
a time and rest of all threads cannot perform other operations on the ArrayList until the first thread
release the lock. This causes overhead and reduces performance. This applies for all collections.

Example : import java.util.*;


class vactor
{
public static void main(String args[])
{
Vector v1 = new Vector();
v1.add(11);
v1.add(12);

// addElement() method is used to append a specified element to the


end
v1.addElement(25);

Vector v2 = new Vector();


v2.add(1);
v2.add(2);

v1.addAll(v2);
System.out.println("Vactor V1 "+v1);

CSIT Dept. GITA Autonomous College Prof. Debasish Das


7

System.out.println("Index of 1 "+v1.indexOf(1));
System.out.println("Size of Vactor V1 "+v1.size());
System.out.println("Capacity is: "+v1.capacity());
System.out.println("is Vactor V1 empty "+v1.isEmpty());
System.out.println("15 is contain Vactor V1
"+v1.contains(15));
System.out.println("11 is contain Vactor V1
"+v1.contains(11));

System.out.println("\nVector elements are:");


Enumeration e = v1.elements();
while (e.hasMoreElements())
System.out.println(e.nextElement());

}
}

stack
 The stack is a linear data structure that is used to store the collection of objects. It is
based on Last-In-First-Out (LIFO).
 Java collection framework provides many interfaces and classes to store the collection
of objects.
 In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program.
 The stack data structure has the two most important operations that are push and pop.
The push operation inserts an element into the stack and pop operation removes an
element from the top of the stack.

CSIT Dept. GITA Autonomous College Prof. Debasish Das


8

Creation of stack
Stack stk = new Stack();
Or
Stack<type> stk = new Stack<type>();
import java.util.*;
class stack1{

public static void main(String args[])


{
Stack s1 = new Stack();

boolean r = s1.empty();
System.out.println("Is the stack empty? " + r);
// items to push
s1.push("Dell");
s1.push("HP");
s1.push("HCL");
s1.push("lenovo");

//prints elements of the stack


System.out.println("Elements in Stack: " + s1);
r = s1.empty();
System.out.println("Is the stack empty? " + r);

System.out.print("pop -> ");


//System.out.println("Popped element: "+ s1.pop());
System.out.println("Peeked element: "+ s1.peek());
/*
// Access element from the top of the stack
Integer t = (Integer)s1.peek();
//prints stack
System.out.println("Element at top: " + t); */

// Search an element
int loc = s1.search("HCL");
System.out.println("Location of Dell: " + loc);
// Find the size of the Stack
int s =s1.size();
System.out.println("The stack size is: "+s);

CSIT Dept. GITA Autonomous College Prof. Debasish Das


9

}
O/P :
Is the stack empty? true
Elements in Stack: [Dell, HP, HCL, lenovo]
Is the stack empty? false
pop -> Peeked element: lenovo
Location of Dell: 2
The stack size is: 4

Queue
 A Queue is designed in such a way so that the elements added to it are placed at the end of
Queue and removed from the beginning of Queue.
 The concept here is similar to the queue we see in our daily life, for example, when a new
iPhone launches we stand in a queue outside the apple store, whoever is added to the queue has
to stand at the end of it and persons are served on the basis of FIFO (First In First Out), The
one who gets the iPhone is removed from the beginning of the queue.

Queue interface in Java collections has two


implementation: LinkedList and PriorityQueue, these two classes implements
Queue interface.
Queue is an interface so we cannot instantiate it, rather we create instance
of LinkedList or PriorityQueue and assign it to the Queue like this:

Queue q1 = new LinkedList();


Queue q2 = new PriorityQueue();

import java.util.*;
class queue
{

public static void main(String[] args)


{

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

//Adding elements to the Queue


q.add("TopRamon");

CSIT Dept. GITA Autonomous College Prof. Debasish Das


10

q.add("Maggie");
q.add("Yappie");
q.add("yoymee");
q.add("knorr");

System.out.println("Elements in Queue:"+q);
System.out.println("Removed element: "+q.remove());
System.out.println("Head: "+q.element());
System.out.println("poll(): "+q.poll());
}
}
Example : 2
import java.util.*;
class queue2
{
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());
}
}
}
Java Comparable interface
Java Comparable interface is used to order the objects of the user-defined class. This interface
is found in java.lang package and contains only one method named compareTo(Object). It
provides a single sorting sequence only, i.e., you can sort the elements on the basis of single
data member only. For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method


public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns
1. positive integer, if the current object is greater than the specified object.
2. negative integer, if the current object is less than the specified object.
3. zero, if the current object is equal to the specified object.
import java.util.*;
class Book implements Comparable<Book>
{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity)
{
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;

CSIT Dept. GITA Autonomous College Prof. Debasish Das


11

this.quantity = quantity;
}
public int compareTo(Book b)
{
System.out.println("object "+b);
System.out.println("ID "+id);
if(id>b.id)
{
return 1;
}
else if(id<b.id)
{
return -1;
}
else

return 0;
}

public class book_queue


{
public static void main(String[] args)
{
Queue<Book> queue = new <Book>PriorityQueue();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
//Adding Books to the queue
queue.add(b1);
queue.add(b2);
queue.add(b3);
System.out.println("Traversing the queue elements:"+queue);
//Traversing queue elements
for(Book b:queue)
{
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+"
"+b.quantity);
}

}
}

TreeSet
TreeSet class used to store unique elements in ascending order. It is similar
to HashSet except that it sorts the elements in the ascending order while HashSet doesn’t
maintain any order.

Java TreeSet class implements the Set interface and use tree based data structure storage. It
extends AbstractSet class and implements the NavigableSet interface. Some important Points

1. It stores the elements in ascending order.


2. It uses a Tree structure to store elements.
3. It contains unique elements only like HashSet.
4. It's access and retrieval times are quite fast.
5. It doesn't allow null element.
6. It is non synchronized.

CSIT Dept. GITA Autonomous College Prof. Debasish Das


12

Method Description
boolean add(E e) It adds the specified element to this set if it is not already present.
boolean addAll(Collection<? extends E> c) It adds all of the elements in the specified collection to this set.
E pollFirst() It is used to retrieve and remove the lowest(first) element.
E pollLast() It is used to retrieve and remove the highest(last) element.
boolean contains(Object o) It returns true if this set contains the specified element.
boolean isEmpty() It returns true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
void clear() It is used to remove all of the elements from this set.
Object clone() It returns a shallow copy of this TreeSet instance.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.
Example :1

import java.util.*;
public class tree
{
public static void main(String[] args)
{
//Creating a TreeSet

TreeSet<Integer> set = new TreeSet<Integer>();

//Adding elements to TreeSet

set.add(20);

set.add(10);

set.add(40);

set.add(80);

set.add(30);

//Printing elements of TreeSet

System.out.println(set); //Output : [10, 20, 30, 40, 80]

//Notice that elements are placed in the sorted order.


}
}
Example : 2
import java.util.*;
public class tree2
{
public static void main(String[] args)
{
//Creating a TreeSet
TreeSet<Object> set = new TreeSet<Object>();
//Adding elements to TreeSet

set.add("kkk"); //inserting String type element

set.add(10); //inserting Integer type element

set.add(new Object()); //inserting Object type element

set.add(20.65); //inserting Double type element

CSIT Dept. GITA Autonomous College Prof. Debasish Das


13

//The elements inserted are not mutually comparable. So, it


will throw ClassCastException.
System.out.println(set);

//Traversing elements
/*Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}*/
}
}
Example :3
import java.util.*;
class tree_3
{
public static void main(String args[])
{
TreeSet <Integer> T = new TreeSet<Integer>();
T.add(23);
T.add(66);
T.add(85);
T.add(10);
T.add(25);

System.out.println(T);

T.remove(23);
System.out.println("After Removing: "+T);

boolean t = T.contains(85);
System.out.println("Is contain Ravi: "+t);

int h =T.pollFirst();

System.out.println("Highest Value: "+h);


System.out.println("Lowest Value: "+T.pollLast());

Iterator itr = T.iterator();


while(itr.hasNext())
{
System.out.println(itr.next());
}

Java HashMap
 HashMap <K, V> is a part of Java’s collection since Java 1.2. This class is found in
java.util package.

CSIT Dept. GITA Autonomous College Prof. Debasish Das


14

 It provides the basic implementation of the Map interface of Java. It stores the data in
(Key, Value) pairs, and you can access them by an index of another type (e.g. an
Integer). One object is used as a key (index) to another object (value). If you try to insert
the duplicate key, it will replace the element of the corresponding key.
 HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key. Since
Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It
inherits the AbstractMap class and implements the Map interface

Points to remember
 Java HashMap contains values based on the key.
 Java HashMap contains only unique keys.
 Java HashMap may have one null key and multiple null values.
 Java HashMap is non synchronized.
 Java HashMap maintains no order.
import java.util.HashMap;
public class hash1
{
public static void main(String[] args)
{
// Create an empty hash map by declaring object of string and
integer type
HashMap<String, Integer> map = new HashMap<>();

// Adding elements to the Map using standard add() method


map.put("Gyana", 10);
map.put("Ashutosh", 30);
map.put("Bibhash", 20);

// Print size and content of the Map


System.out.println("Size of map is:- "+ map.size());

// Printing elements in object of Map


System.out.println(map);

// Checking if a key is present and if present, print value by


passing random element
if (map.containsKey("vishal"))
{

// Mapping
Integer a = map.get("vishal");

// Printing value fr the corresponding key


System.out.println("value for key" + " \"vishal\" is:- " + a);
}
else
System.out.println("not found ");

}
}

Example-2
import java.util.HashMap;

CSIT Dept. GITA Autonomous College Prof. Debasish Das


15

public class hash2


{
public static void main(String[] args)
{
// Create an empty hash map by declaring object of string and
integer type
HashMap <Integer,String> people = new HashMap<>();
// Add keys and values (Name, Age)
people.put(32,"Janvi");
people.put(30,"Ananya");
people.put(33,"Aishwarya");

for (Integer i : people.keySet())


{
System.out.println("key: " + i + " value: " + people.get(i));
}

people.put(34,"Niha_kakar");
people.put(33,"Goutami");
people.put(36,"Dinesh");
// Printing elements in object of Map
System.out.println(people);

//To remove an item, use the remove() method and refer to the key:
System.out.println("Deleted item "+people.remove(36));

//To remove all items, use the clear() method:


people.clear();
System.out.println("All items "+people);
}
}

CSIT Dept. GITA Autonomous College Prof. Debasish Das

You might also like