0% found this document useful (0 votes)
2 views43 pages

Collections

The document provides an overview of the Java Collections framework, which allows for the storage and manipulation of groups of objects through various interfaces and classes. It outlines the advantages of using the framework, such as a consistent API and improved programming efficiency, and details methods available in the Collection, Iterator, and ArrayList interfaces. Additionally, it includes examples of how to use ArrayLists in Java, demonstrating various methods and functionalities.

Uploaded by

ishikajanit
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views43 pages

Collections

The document provides an overview of the Java Collections framework, which allows for the storage and manipulation of groups of objects through various interfaces and classes. It outlines the advantages of using the framework, such as a consistent API and improved programming efficiency, and details methods available in the Collection, Iterator, and ArrayList interfaces. Additionally, it includes examples of how to use ArrayLists in Java, demonstrating various methods and functionalities.

Uploaded by

ishikajanit
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 43

Collections in Java

Any group of individual objects that are represented as a single unit is


known as a Java Collection of Objects. 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 searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is a framework in Java


A framework is a set of classes and interfaces which provide a ready-made
architecture.

Hierarchy of Collection Framework


The utility package, (java.util) contains all the classes and interfaces that
are required by the collection framework. The collection framework
contains an interface named an iterable interface which provides the
iterator to iterate through all the collections. This interface is extended by
the main collection interface which acts as a root for the collection
framework. All the collections extend this collection interface thereby
extending the properties of the iterator and the methods of this interface.
The following figure illustrates the hierarchy of the collection framework.

1
Advantages of the Java Collection Framework

Since the lack of a collection framework leads to, the standard methods
for grouping Java objectsusing Arrays or Vectors, or Hashtables. All of
these collections had no common interface. Therefore, though the main
aim of all the collections is the same, the implementation of all these
collections was defined independently and had no correlation among
them. And also, it is very difficult for the users to remember all the
different methods, syntax, and constructors present in every collection
class.
the following are the advantages of the collection framework.

1. Consistent API: The API has a basic set of interfaces


like Collection, Set, List, or Map, all the classes (ArrayList, LinkedList,
Vector, etc) that implement these interfaces have some common set
of methods.
2. Reduces programming effort: A programmer doesn’t have to worry
about the design of the Collection but rather he can focus on its best
use in his program. Therefore, the basic concept of Object-oriented
programming (i.e.) abstraction has been successfully implemented.
3. Increases program speed and quality: Increases performance by
providing high-performance implementations of useful data structures
and algorithms because in this case, the programmer need not think
of the best implementation of a specific data structure. He can simply
use the best implementation to drastically boost the performance of
his algorithm/program.

Methods of Collection interface


This interface contains various methods which can be directly used by all
the collections which implement this interface. They are:

Method Description

This method is used to add an object


add(Object)
to the collection.

This method adds all the elements in


addAll(Collection c)
the given collection to this collection.

This method removes all of the


clear()
elements from this collection.

contains(Object o) This method returns true if the


collection contains the specified

2
Method Description

element.

This method returns true if the


containsAll(Collection c) collection contains all of the elements
in the given collection.

This method compares the specified


equals(Object o)
object with this collection for equality.

This method is used to return the hash


hashCode()
code value for this collection.

This method returns true if this


isEmpty()
collection contains no elements.

This method returns an iterator over


iterator()
the elements in this collection.

This method is used to return the


max()
maximum value present in the
collection.

This method returns a parallel Stream


parallelStream()
with this collection as its source.

This method is used to remove the


given object from the collection. If
remove(Object o) there are duplicate values, then this
method removes the first occurrence
of the object.

This method is used to remove all the


removeAll(Collection c) objects mentioned in the given
collection from the collection.

This method is used to remove all the


removeIf(Predicate filter) elements of this collection that satisfy
the given predicate.

retainAll(Collection c) This method is used to retain only the

3
Method Description

elements in this collection that are


contained in the specified collection.

This method is used to return the


size()
number of elements in the collection.

This method is used to create


spliterator() a Spliterator over the elements in this
collection.

This method is used to return a


stream() sequential Stream with this collection
as its source.

This method is used to return an array


toArray() containing all of the elements in this
collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean It returns true if the iterator has more elements


hasNext() otherwise it returns false.

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

3 public void It removes the last elements returned by the


remove() iterator. It is less used.

4
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the
subclasses of Collection interface also implement the Iterable interface.

It contains only one abstract method. i.e.

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface
The Collection interface is the interface which is implemented by all the
classes in the collection framework. It declares the methods that every
collection will have. In other words, we can say that the Collection
interface builds the foundation on which the collection framework
depends.

Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by
all the subclasses of Collection interface.

List Interface
List interface is the child interface of Collection interface. It inhibits a list
type data structure in which we can store the ordered collection of objects.
It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector,


and Stack.

To instantiate the List interface, we must use :

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


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

ArrayList
ArrayList provides us with dynamic arrays in Java. Though, it may be
slower than standard arrays but can be helpful in programs where lots of
manipulation in the array is needed. The size of an ArrayList is increased

5
automatically if the collection grows or shrinks if the objects are removed
from the collection. Java ArrayList allows us to randomly access the list.
ArrayList can not be used for primitive types, like int, char, etc. We will
need a wrapper class for such cases.

The important points about the Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because the array works on an index
basis.
o 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.
o 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:

o ArrayList<int> al = ArrayList<int>(); // does not work


o ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

6
Constructors of ArrayList
Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? It is used to build an array list that is initialized


extends E> c) with the elements of the collection c.

ArrayList(int capacity) It is used to build an array list that has the


specified initial capacity.

Methods of ArrayList
Method Description

void add(int index, E element) It is used to insert the specified element at


the specified position in a list.

boolean add(E e) It is used to append the specified element at


the end of a list.

boolean addAll(Collection<? It is used to append all of the elements in the


extends E> c) specified collection to the end of this list, in
the order that they are returned by the
specified collection's iterator.

boolean addAll(int index, It is used to append all the elements in the


Collection<? extends E> c) specified collection, starting at the specified
position of the list.

void clear() It is used to remove all of the elements from


this list.

7
void ensureCapacity(int When methods such as add() and addAll() are
requiredCapacity) called, if the capacity of a list is not large
enough then some extra work is done to add
enough space for the new items. It takes a bit
of time to do this, so having this happen with
every add() call is not ideal.

E get(int index) It is used to fetch the element from the


particular position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise


false.

Iterator() An Iterator is an object that can be used to


loop through collections, like ArrayList and
HashSet. It is called an "iterator" because
"iterating" is the technical term for looping.

listIterator() The listIterator () method of Java ArrayList


returns a list iterator over the elements in this
list starting at the specified position in this
list. The specified index indicates the first
element that would be returned by an initial
call to next. An initial call to previous would
return the element with the specified index
minus one.

int lastIndexOf(Object o) It is used to 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[] toArray() It is used to return an array containing all of


the elements in this list in the correct order.

boolean contains(Object o) Is used for checking if the specified element


exists in the given list or not. It returns true if
the list contains the specified element.

int indexOf(Object o) It is used to return the index in this list of the


first occurrence of the specified element, or -
1 if the List does not contain this element.

E remove(int index) It is used to remove the element present at


the specified position in the list.

8
boolean remove(Object o) It is used to remove the first occurrence of
the specified element.

boolean removeAll(Collection< The removeAll() method removes all items


?> c) from a list which belong to a specified
collection.

protected It is used to remove all the elements lies


void removeRange(int within the given range.
fromIndex, int toIndex)

void retainAll(Collection<?> c) The retainAll () method of Java ArrayList


class keeps only elements in the original list
that are contained in the specified collection.
In other words, it replaces the original list
with the specified list.

E set(int index, E element) It is used to replace the specified element in


the list, present at the specified position.

void sort(Comparator<? super It is used to sort the elements of the list on


E> c) the basis of the specified comparator.

List<E> subList(int fromIndex, It is used to fetch all the elements that lies
int toIndex) within the given range.

int size() It is used to return the number of elements


present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList


instance to be the list's current size.

ArrayList Example0
import java.util.ArrayList;
import java.util.Iterator;

9
import java.util.ListIterator;
public class ArrayListExampleOne {

public static void main(String[] args) {


// TODO Auto-generated method stub

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


arrlst.add("A");
arrlst.add("B");
arrlst.add("C");
arrlst.add("D");
arrlst.add("E");
arrlst.add("F");

Iterator <String> itr = arrlst.iterator();


while(itr.hasNext()) {
System.out.println(itr.next());
}
ArrayList <Integer> arrlst1 = new ArrayList<Integer>();
arrlst1.add(1);
arrlst1.add(2);
arrlst1.add(3);
arrlst1.add(4);
//System.out.println(arrlst1);
Iterator <Integer> itr1 = arrlst1.iterator();
while(itr1.hasNext()) {
System.out.println(itr1.next());
}}}

ArrayList Example1

10
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListExampleOne {

public static void main(String[] args) {


// TODO Auto-generated method stub
// Declaring ArrayList for String types of element
ArrayList <String> state = new ArrayList<String>();

//Adding values to the ArrayList


state.add("Delhi");
state.add("UP");
state.add("MP");
state.add("Delhi");

//Adding values to ArrayList at particular index


state.add(1,"UK");

//printing all values of the ArrayList


System.out.println(state);

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


state2.add("BH");
state2.add(1, "RJ");

// Adding all elements of one ArrayList to another ArrayList


state2.addAll(state);

//Adding all elements of one ArrayList to another ArrayList at


particular index

11
state2.addAll(3,state);

System.out.println(state2);

// Removing all element from the ArrayList named state2


state2.clear();
System.out.println(state2);

// Finding out the element at particular index in a ArrayList


System.out.println(state.get(1));

//Checking whether a a ArrrayList is empty or not


System.out.println("Is Arraylist state empty:
"+state.isEmpty());

// Printing all elements of the ArrayList with the help of Iterator


System.out.println("Following are printed with the help of
iterator");
Iterator <String> iterator = state.iterator();
while(iterator.hasNext()) {

System.out.println(iterator.next());
}

// Accessing elements using ListIterator


System.out.println("Following are printed with the help of
Listiterator");
ListIterator<String> listerator = state.listIterator(2);
while(listerator.hasNext()) {
System.out.println(listerator.next());
}

12
// Finding the last index of an element in a ArrayList
int index =state.indexOf("Delhi");
System.out.println("Index for element Delhi is:
"+index);

// Finding the last index of an element in a ArrayList


int i =state.lastIndexOf("Delhi");
System.out.println("last index for element Delhi is: "+i);

int j =state.lastIndexOf("Mumbai");
System.out.println("last index for element Mumbai is: "+j);

// Removing an element present at a particular index


state.remove(1);
System.out.println("I have removed UK");
System.out.println(state);

// Removing an element by using it's value

state.remove("MP");
System.out.println("I have removed MP");
System.out.println(state);

//Finding out size of the ArrayList


int length = state.size();

//Converting ArrayList into an array


String [] stateArray = new String [length];
stateArray = state.toArray(stateArray);

13
//Accessing element of the array using for each loop
for(String item:stateArray) {
System.out.println(item);
}

//Checking whether an element is present in a a ArrrayList or


not

boolean b = state.contains("Delhi");
System.out.println("Delhi is an element of the ArrayList state:
"+b);
} }
ArrayListExample2

ArrayListExample2
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListExampleOne {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList <String> arrlst = new ArrayList<String>();
arrlst.add("A");
arrlst.add("B");
arrlst.add("C");
arrlst.add("D");
arrlst.add("E");
arrlst.add("F");

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

14
arrlst1.add("E");
arrlst1.add("G");
arrlst1.add("H");

arrlst.removeAll(arrlst1);
System.out.println(arrlst);
arrlst.removeRange(0, 2);
arrlst. retainAll(arrlst1);
}

ArrayListExample3
import java.util.*;

public class test {


public static void main(String[] args) {

// create an empty array list with an initial capacity


ArrayList<String> color_list = new ArrayList<String>(5);

// use add() method to add values in the list


color_list.add("White");
color_list.add("Black");
color_list.add("Red");
color_list.add("White");
color_list.add("Yellow");

// Change the Red color to Violet


color_list.set(2, new String("Violet"));

// Print out the colors in the ArrayList


for (int i = 0; i < 5; i++)
{
System.out.println(color_list.get(i).toString());
}
}
}

15
Java LinkedList 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.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting
needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

Constructors of Java LinkedList


Constructor Description

LinkedList() It is used to construct an empty list.

16
LinkedList(Collection<? It is used to construct a list containing the elements
extends E> c) of the specified collection, in the order, they are
returned by the collection's iterator.

Methods of Java LinkedList


Methods of Java LinkedList
Method Description

boolean add(E e) It is used to append the specified element to the


end of a list.

void add(int index, E It is used to insert the specified element at the


element) specified position index in a list.

boolean It is used to append all of the elements in the


addAll(Collection<? specified collection to the end of this list, in the
extends E> c) order that they are returned by the specified
collection's iterator.

boolean It is used to append all of the elements in the


addAll(Collection<? specified collection to the end of this list, in the
extends E> c) order that they are returned by the specified
collection's iterator.

boolean addAll(int index, It is used to append all the elements in the


Collection<? extends E> specified collection, starting at the specified
c) position of the list.

void addFirst(E e) It is used to insert the given element at the


beginning of a list.

void addLast(E e) It is used to append the given element to the end


of a list.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It is used to return true if a list contains a


specified element.

17
Iterator<E> It is used to return an iterator over the elements
descendingIterator() in a deque in reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified


position in a list.

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first


occurrence of the specified element, or -1 if the
list does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last


occurrence of the specified element, or -1 if the
list does not contain any element.

ListIterator<E> It is used to return a list-iterator of the elements


listIterator(int index) in proper sequence, starting at the specified
position in the list.

boolean offer(E e) It adds the specified element as the last element


of a list.

boolean offerFirst(E e) It inserts the specified element at the front of a


list.

boolean offerLast(E e) It inserts the specified element at the end of a list.

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns


null if a list is empty.

E peekLast() It retrieves the last element of a list or returns null


if a list is empty.

E poll() It retrieves and removes the first element of a list.

18
E pollFirst() It retrieves and removes the first element of a list,
or returns null if a list is empty.

E pollLast() It retrieves and removes the last element of a list,


or returns null if a list is empty.

E pop() It pops an element from the stack represented by


a list.

void push(E e) It pushes an element onto the stack represented


by a list.

E remove() It is used to retrieve and removes the first


element of a list.

E remove(int index) It is used to remove the element at the specified


position in a list.

boolean remove(Object o) It is used to remove the first occurrence of the


specified element in a list.

E removeFirst() It removes and returns the first element from a


list.

boolean It is used to remove the first occurrence of the


removeFirstOccurrence(Ob specified element in a list (when traversing the
ject o) list from head to tail).

E removeLast() It removes and returns the last element from a


list.

boolean It removes the last occurrence of the specified


removeLastOccurrence(Ob element in a list (when traversing the list from
ject o) head to tail).

E set(int index, E element) It replaces the element at the specified position in


a list with the specified element.

Object[] toArray() It is used to return an array containing all the


elements in a list in proper sequence (from first to
the last element).

<T> T[] toArray(T[] a) It returns an array containing all the elements in

19
the proper sequence (from first to the last
element); the runtime type of the returned array
is that of the specified array.

int size() It is used to return the number of elements in a


list.

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain
insertion order. Both are non-synchronized classes.

However, there are many differences between the ArrayList and LinkedList
classes that are given below.

ArrayList LinkedList

1) ArrayList internally uses LinkedList internally uses


a dynamic array to store the a doubly linked list to store the
elements. elements.

2) Manipulation with ArrayList Manipulation with LinkedList


is slow because it internally uses an is faster than ArrayList because
array. If any element is removed it uses a doubly linked list, so no
from the array, all the other bit shifting is required in
elements are shifted in memory. memory.

3) An ArrayList class can act as a LinkedList class can act as a list


list only because it implements List and queue both because it
only. implements List and Deque
interfaces.

4) ArrayList is better for storing LinkedList is better for


and accessing data. manipulating data.

5) The memory location for the The location for the elements of a
elements of an ArrayList is linked list is not contagious.
contiguous.

6) Generally, when an ArrayList is There is no case of default


initialized, a default capacity of 10 is capacity in a LinkedList. In
assigned to the ArrayList. LinkedList, an empty list is
created when a LinkedList is
initialized.

20
7) To be precise, an ArrayList is a LinkedList implements the doubly
resizable array. linked list of the list interface.

Points to Remember
The following are some important points to remember regarding an
ArrayList and LinkedList.

o When the rate of addition or removal rate is more than the read
scenarios, then go for the LinkedList. On the other hand, when the
frequency of the read scenarios is more than the addition or removal
rate, then ArrayList takes precedence over LinkedList.
o Since the elements of an ArrayList are stored more compact as
compared to a LinkedList; therefore, the ArrayList is more cache-
friendly as compared to the LinkedList. Thus, chances for the cache
miss are less in an ArrayList as compared to a LinkedList. Generally,
it is considered that a LinkedList is poor in cache-locality.
o Memory overhead in the LinkedList is more as compared to the
ArrayList. It is because, in a LinkedList, we have two extra links (next
and previous) as it is required to store the address of the previous
and the next nodes, and these links consume extra space. Such links
are not present in an ArrayList.

21
Java HashSet

Java HashSet class is used to create a collection that uses a hash table for
storage. It inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are
inserted on the basis of their hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is
0.75.

A list can contain duplicate elements whereas Set


contains unique elements only.

22
Constructors of Java HashSet class
SN Constructor Description

1) HashSet() It is used to construct a default HashSet.

2) HashSet(int It is used to initialize the capacity of the hash


capacity) set to the given integer value capacity. The
capacity grows automatically as elements are
added to the HashSet.

3) HashSet(int It is used to initialize the capacity of the hash


capacity, float set to the given integer value capacity and
loadFactor) the specified load factor.

4) HashSet(Collectio It is used to initialize the hash set by using the


n<? extends E> c) elements of the collection c.

Methods of Java HashSet class

SN Modifier & Method Description


Type

1) boolean add(E e) It is used to add the specified element to


this set if it is not already present.

2) void clear() It is used to remove all of the elements


from the set.

3) boolean contains(Obj It is used to return true if this set contains


ect o) the specified element.

4) boolean isEmpty() It is used to return true if this set contains


no elements.

5) Iterator<E> iterator() It is used to return an iterator over the


elements in this set.

6) boolean remove(Obje It is used to remove the specified element

23
ct o) from this set if it is present.

7) int size() It is used to return the number of


elements in the set.

24
Java LinkedHashSet Class
Java LinkedHashSet class is a Hashtable and Linked list implementation of
the Set interface. It inherits the HashSet class and implements the Set
interface.

The important points about the Java LinkedHashSet class are:

o Java LinkedHashSet class contains unique elements only like HashSet.


o Java LinkedHashSet class provides all optional set operations and permits
null elements.
o Java LinkedHashSet class is non-synchronized.
o Java LinkedHashSet class maintains insertion order.

Note: Keeping the insertion order in the LinkedHashset has some additional costs,
both in terms of extra memory and extra CPU cycles. Therefore, if it is not required
to maintain the insertion order, go for the lighter-weight HashMap or the HashSet
instead.

Difference between HashSet and LinkedHashSet


Property HashSet LinkedHashSet

Data structure It uses a Hashtable to It uses a HashTable and


store the elements. doubly linked list to store
and maintain the insertion
order of the elements.

Technique to Hashing Hashing


store the
elements

Insertion Order It does not provide It provides an insertion


any insertion order. order; we can predict the
We can not predict order of elements.
the order of elements.

Null elements It allows only one null It also allows only one null
element. element.

Memory It requires less It requires more memory


memory. than HashSet.

Performance It provides slightly It provides low


faster performance performance than HashSet

25
than LinkedHashSet

Synchronized Non-synchronized Non-synchronized

Complexity for O (1) O (1)


the insertion,
removal,
retrieval
operations

Declaration HashSet obj = new LinkedHashSet obj = new


HashSet(); LinkedHashSet();

Extends AbstractSet class HashSet class

Implements Set interface Set interface

Initial Capacity 16 16

Package java.util Java.util

26
Java TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It
inherits AbstractSet class and implements the NavigableSet interface. The
objects of the TreeSet class are stored in ascending order.
The important points about the Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.
o The TreeSet can only allow those generic types that are comparable.
For example The Comparable interface is being implemented by the
StringBuffer class.

Internal Working of The TreeSet Class


TreeSet is being implemented using a binary search tree, which is self-
balancing just like a Red-Black Tree. Therefore, operations such as a
search, remove, and add consume O(log(N)) time. The reason behind this
is there in the self-balancing tree. It is there to ensure that the tree height
never exceeds O(log(N)) for all of the mentioned operations. Therefore, it
is one of the efficient data structures in order to keep the large data that is
sorted and also to do operations on it.

PriorityQueue in Java
A PriorityQueue is used when the objects are supposed to be processed
based on the priority. It is known that a Queue follows the First-In-First-Out
algorithm, but sometimes the elements of the queue are needed to be
processed according to the priority, that’s when the PriorityQueue comes
into play.

The PriorityQueue is based on the priority heap. The elements of the


priority queue are ordered according to the natural ordering, or by a
Comparator provided at queue construction time, depending on which
constructor is used.

27
A few important points on Priority Queue are as follows:
 PriorityQueue doesn’t permit null.
 We can’t create a PriorityQueue of Objects that are non-comparable
 PriorityQueue are unbound queues.
 The head of this queue is the least element with respect to the
specified ordering. If multiple elements are tied for the least value, the
head is one of those elements — ties are broken arbitrarily.
 The queue retrieval operations poll, remove, peek,
and element access the element at the head of the queue.
 It provides O(log(n)) time for add and poll methods.

Constructors:
1. PriorityQueue(): Creates a PriorityQueue with the default initial
capacity (11) that orders its elements according to their natural ordering.
PriorityQueue<E> pq = new PriorityQueue<E>();
2. PriorityQueue(Collection<E> c): Creates a PriorityQueue
containing the elements in the specified collection.
PriorityQueue<E> pq = new PriorityQueue<E>(Collection<E> c);
3. PriorityQueue(int initialCapacity): Creates a PriorityQueue with the
specified initial capacity that orders its elements according to their
natural ordering.
PriorityQueue<E> pq = new PriorityQueue<E>(int initialCapacity);
4. PriorityQueue(int initialCapacity, Comparator<E>
comparator): Creates a PriorityQueue with the specified initial capacity
that orders its elements according to the specified comparator.
PriorityQueue<E> pq = new PriorityQueue(int initialCapacity,
Comparator<E> comparator);
5. PriorityQueue(PriorityQueue<E> c): Creates a PriorityQueue
containing the elements in the specified priority queue.
PriorityQueue<E> pq = new PriorityQueue(PriorityQueue<E> c);

Methods in PriorityQueue class

METHOD DESCRIPTION

add(E e) Inserts the specified element into this priority queue.

clear() Removes all of the elements from this priority queue.

comparator() Returns the comparator used to order the elements in

28
METHOD DESCRIPTION

this queue, or null if this queue is sorted according to


the natural ordering of its elements.

contains?(Object Returns true if this queue contains the specified


o) element.

iterator() Returns an iterator over the elements in this queue.

offer?(E e) Inserts the specified element into this priority queue.

remove?(Object Removes a single instance of the specified element


o) from this queue, if it is present.

Real Time Examples:

Priority Queue is a data structure in which elements are ordered by


priority, with the highest-priority elements appearing at the front of the
queue. Here are some real-world examples of where priority queues can
be used:
 Task Scheduling: In operating systems, priority queues are used to
schedule tasks based on their priority levels. For example, a high-
priority task like a critical system update may be scheduled ahead of a
lower-priority task like a background backup process.
 Emergency Room: In a hospital emergency room, patients are
triaged based on the severity of their condition, with those in critical
condition being treated first. A priority queue can be used to manage
the order in which patients are seen by doctors and nurses.
 Network Routing: In computer networks, priority queues are used to
manage the flow of data packets. High-priority packets like voice and
video data may be given priority over lower-priority data like email
and file transfers.
 Transportation: In traffic management systems, priority queues can
be used to manage traffic flow. For example, emergency vehicles like
ambulances may be given priority over other vehicles to ensure that
they can reach their destination quickly.
 Job Scheduling: In job scheduling systems, priority queues can be
used to manage the order in which jobs are executed. High-priority

29
jobs like critical system updates may be scheduled ahead of lower-
priority jobs like data backups.
 Online Marketplaces: In online marketplaces, priority queues can be
used to manage the delivery of products to customers. High-priority
orders like express shipping may be given priority over standard
shipping orders.

30
Map Interface in Java
In Java, Map Interface is present in java.util package represents a
mapping between a key and a value. Java Map interface is not a subtype
of the Collection interface. Therefore it behaves a bit differently from the
rest of the collection types. A map contains unique keys. 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.
Maps are perfect to use for key-value association mapping such as
dictionaries. The maps are used to perform lookups by keys or when
someone wants to retrieve and update elements by keys. Some common
scenarios are as follows:
 A map of error codes and their descriptions.
 A map of zip codes and cities.
 A map of managers and employees. Each manager (key) is associated
with a list of employees (value) he manages.
 A map of classes and students. Each class (key) is associated with a
list of students (value).

Creating Map Objects


Since Map is an interface, objects cannot be created of the type map. We
always need a class that extends this map in order to create an object.

Characteristics of a Map Interface

1. A Map cannot contain duplicate keys and each key can map to at most
one value. Some implementations allow null key and null values like
the HashMap and LinkedHashMap, but some do not like the TreeMap.

31
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders,
while HashMap does not.
3. There are two interfaces for implementing Map in Java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.

Methods in Java Map Interface


Method Action Performed

This method is used in Java Map


Interface to clear and remove all of the
clear()
elements or mappings from a specified
Map collection.

This method is used in Map Interface in


Java to check whether a particular key
is being mapped into the Map or not. It
containsKey(Object)
takes the key element as a parameter
and returns True if that element is
mapped in the map.

This method is used in Map Interface to


check whether a particular value is
being mapped by a single or more than
containsValue(Object) one key in the Map. It takes the value as
a parameter and returns True if that
value is mapped by any of the keys in
the map.

This method is used in Map Interface in


Java to create a set out of the same
elements contained in the map. It
entrySet()
basically returns a set view of the map
or we can create a new set and store
the map elements into them.

get(Object) This method is used to retrieve or fetch


the value mapped by a particular key
mentioned in the parameter. It returns

32
Method Action Performed

NULL when the map contains no such


mapping for the key.

This method is used to check if a map is


having any entry for key and value
isEmpty()
pairs. If no mapping exists, then this
returns true.

This method is used in Java Map


put(Object, Object) Interface to associate the specified
value with the specified key in this map.

This method is used in Map Interface in


putAll(Map) Java to copy all of the mappings from
the specified map to this map.

This method is used in Map Interface to


remove(Object) remove the mapping for a key from this
map if it is present in the map.

This method is used to return the


size() number of key/value pairs available in
the map.

If the specified key is not already


associated with a value (or is mapped
putIfAbsent(K key, V value) to null) associates it with the given
value and returns null, else returns the
current associate value.

33
HashMap in Java
HashMap provides the basic implementation of the Map interface of
Java. HashMap in Java 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 in HashMap, it will replace the element of the
corresponding key.

HashMap is a part of the Java collection framework. It uses a technique


called Hashing. It implements the map interface. It stores the data in the
pair of Key and Value. HashMap contains an array of the nodes, and the
node is represented as a class. It uses an array and LinkedList data
structure internally for storing Key and Value. There are four fields in
HashMap.

Characteristics of Java HashMap


A HashMap is a data structure that is used to store and retrieve values
based on keys. Some of the key characteristics of a hashmap include:
 Fast access time: HashMaps provide constant time access to
elements, which means that retrieval and insertion of elements are
very fast, usually O(1) time complexity.
 Uses hashing function: HashMaps uses a hash function to map keys
to indices in an array. This allows for a quick lookup of values based on
keys.
 Stores key-value pairs: Each element in a HashMap consists of a
key-value pair. The key is used to look up the associated value.
 Supports null keys and values: HashMaps allow for null values and
keys. This means that a null key can be used to store a value, and a
null value can be associated with a key.
 Not ordered: HashMaps are not ordered, which means that the order
in which elements are added to the map is not preserved. However,
LinkedHashMap is a variation of HashMap that preserves the insertion
order.
 Allows duplicates: HashMaps allow for duplicate values, but not
duplicate keys. If a duplicate key is added, the previous value
associated with the key is overwritten.
 Thread-unsafe: HashMaps are not thread-safe, which means that if
multiple threads access the same hashmap simultaneously, it can lead
to data inconsistencies. If thread safety is required,
ConcurrentHashMap can be used.
 Capacity and load factor: HashMaps have a capacity, which is the
number of elements that it can hold, and a load factor, which is the
measure of how full the hashmap can be before it is resized.

34
35
Java LinkedHashMap class
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map
interface, with predictable iteration order. It inherits HashMap class and
implements the Map interface.

Points to remember
o Java LinkedHashMap contains values based on the key.
o Java LinkedHashMap contains unique elements.
o Java LinkedHashMap may have one null key and multiple null values.
o Java LinkedHashMap is non synchronized.
o Java LinkedHashMap maintains insertion order. To maintain the order of
elements, the linked hashmap modifies the Map.Entry class of HashMap by
adding pointers to the next and previous entries:
o The initial default capacity of Java HashMap class is 16 with a load factor of
0.75

36
Java TreeMap class

Java TreeMap class is a red-black tree based implementation. It provides


an efficient means of storing key-value pairs in sorted order.

The important points about Java TreeMap class are:

o Java TreeMap contains values based on the key. It implements the


NavigableMap interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null
values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.

37
Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It
inherits Dictionary class and implements the Map interface.

Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The
position of the bucket is identified by calling the hashcode() method.
A Hashtable contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas
loadFactor is 0.75.

38
Java Vector
 The Vector class implements a growable array of objects.
 Vectors fall in legacy classes, but now it is fully compatible with
collections.
 It is found in java.util package and implement the List interface, so we
can use all the methods of the List interface.
 Vector implements a dynamic array which means it can grow or shrink
as required. Like an array, it contains components that can be
accessed using an integer index.
 They are very similar to ArrayList, but Vector is synchronized and has
some legacy methods that the collection framework does not contain.
 It also maintains an insertion order like an ArrayList. Still, it is rarely
used in a non-thread environment as it is synchronized, and due to
this, it gives a poor performance in adding, searching, deleting, and
updating its elements.
 The Iterators returned by the Vector class are fail-fast. In the case of
concurrent modification, it fails and throws
the ConcurrentModificationException.

39
Java 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).
Stack is a class that falls under the Collection framework that extends
the Vector class.
It also implements interfaces List, Collection, Iterable, Cloneable,
Serializable. It represents the LIFO stack of objects.

Method Modifier Method Description


and Type

empty() boolean The method checks the stack is empty or not.

push(E E The method pushes (insert) an element onto the


item) top of the stack.

pop() E The method removes an element from the top of


the stack and returns the same element as the

40
value of that function.

peek() E The method looks at the top element of the stack


without removing it.

search(Obje int The method searches the specified object and


ct o) returns the position of the object.

41
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

o positive integer, if the current object is greater than the specified


object.
o negative integer, if the current object is less than the specified
object.
o zero, if the current object is equal to the specified object.

Java Comparator interface


Java Comparator interface is used to order the objects of a user-defined
class.

This interface is found in java.util package and contains 2 methods


compare(Object obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on
the basis of any data member, for example, rollno, name, age or anything
else.

Properties Class in Java


The Properties class represents a persistent set of properties. The
Properties can be saved to a stream or loaded from a stream. It belongs
to java.util package.

Features of Properties class:


 Properties is a subclass of Hashtable.
 It is used to maintain a list of values in which the key is a string and
the value is also a string i.e; it can be used to store and retrieve string
type data from the properties file.

42
 Properties class can specify other properties list as it’s the default. If a
particular key property is not present in the original Properties list, the
default properties will be searched.
 Properties object does not require external synchronization and
Multiple threads can share a single Properties object.
 Also, it can be used to retrieve the properties of the system.

An Advantage of the properties file


Recompilation is not required if the information is changed from a
properties file: If any information is changed from the properties file, you
don't need to recompile the java class. It is used to store information
which is to be changed frequently.

43

You might also like