Java Unit IV

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

UNIT IV

JAVA COLLECTIONS FRAMEWORK

What is a Collection in Java?

A Collection in Java is a group of Individual objects known as its elements into a single entity.

The Collections in Java provides an architecture to store and manipulate the group of objects, interfaces and
classes. This java collection is a framework.

Eg: a collection is an object or a container that stores a group of other objects.

piggy bank :- piggy bank is called a Collection and the coins are nothing but objects. Technically, a collection is
an object or a container that stores a group of other objects.

JAVA COLLECTION FRAMEWORK:

The Java collections framework provides a set of interfaces and classes to implement various data structures and
algorithms. Collection framework is present in package java. util. package. It was defined in JDK 1.2 version
which is one of the most used frameworks to date.

Collection Framework Hierarchy

The Collection framework is a unified architecture for storing and manipulating a group of objects.

In Java, the Collections Framework is a hierarchy of interfaces and classes that provides easy management of a
group of objects.

The Java collections framework provides various interfaces. These interfaces include several methods to perform
different operations on collections.

Class: A class is a collection of similar types of objects. It is an implementation of the collection interface.
Interface: An interface is the abstract data type. It is at the topmost position in the framework hierarchy.

extends: It is a keyword that is used to develop inheritance between two classes and two interfaces. Inheritance in
Java refers to the concept that one can create new classes that are built upon existing classes.

implements: implements is also a keyword used to develop inheritance between class and interface. A class
implements an interface.

JAVA COLLECTION INTERFACE

The Collection interface is the root interface of the collections framework hierarchy.

Java does not provide direct implementations of the Collection interface but provides implementations of its sub
interfaces like List, Set, and Queue.

The framework includes other interfaces as well: Map and Iterator.


interface Collection<E>

Here, E is the type of object that the collection will hold.

It provides basic operations like adding, removing, clearing the elements in a collection, checking whether the
collection is empty, etc.

Sub interfaces of the Collection Interface:

The Collection interface includes sub interfaces that are implemented by Java classes.

All the methods of the Collection interface are also present in its sub interfaces.

a) List Interface

The List interface is an ordered collection that allows us to add and remove elements like an array.

b) Set Interface

The Set interface allows us to store elements in different sets similar to the set in mathematics. It cannot have
duplicate elements.

c) Queue Interface

The Queue interface is used when we want to store and access elements in First In, First Out manner.

d) Java Map Interface

In Java, the Map interface allows elements to be stored in key/value pairs. Keys are unique names that can be used
to access a particular element in a map.

e) Java Iterator Interface

In Java, the Iterator interface provides methods that can be used to access elements of collections.

Iterator is an object that can be used to loop through collections.

There are 3 methods in the Iterator interface:


public Object next()- It returns the next element in the collection. It throws the exception of
NoSuchElementException if there is no next element.

public void remove()- It removes the current element from the collection.

public boolean hasNext()- It returns true if there are more elements in the collection. Else, returns false.

JAVA COLLECTION VS COLLECTIONS FRAMEWORK


COLLECTION IN JAVA COLLECTIONS FRAMEWORK
Collection in Java is a class. Collections Framework is a framework.
It is a single unit that contains and manipulates a They are used to manipulate collections.
group of objects.
COLLECTIONS VS COLLECTION IN JAVA
COLLECTIONS COLLECTION
"Collections" is actually a utility in java that is in "Collection" is an interface class in java that is also
the java.util.package. in the java.util.package.
"Collections" is a set of methods you can use to The "Collection" can be understood as a single unit
perform different operations on a collection. with a group or a set of objects.
All the methods in "Collections" are static. "Collection" interface got static, default,
and abstract methods. An abstract method is a
method inside an abstract class that was declared
with the abstract keyword
The "Collections" class extends the Object class. The "Collection" interface extends the Iterable
interface.
COLLECTION CLASSES IN JAVA

Java collection framework consists of various classes that are used to store objects. These classes on the
top implements the Collection interface.

Java List

The List interface is a child interface of the Collection interface. The List interface is available inside
the java.util package. It defines the methods that are commonly used by classes like ArrayList, LinkedList,
Vector, and Stack.

 The List interface extends Collection interface.


 The List interface allows duplicate elements.
 The List interface preserves the order of insertion.
 The List allows to access the elements based on the index value that starts with zero.

There are three classes implemented by the list interface and they are given below.

Syntax
List<Data-Type>linkedlist= new LinkedList<Data-Type>();

List<Data-Type>arraylist= new ArrayList<Data-Type>();

List<Data-Type>vector= new Vector<Data-Type>();

ARRAYLIST CLASS OF COLLECTIONS

 ArrayList is similar to Arrays.


 They are also called dynamic arrays.
 It implements the List Interface.
 That means it does not have a fixed size.
 Its size can be increased or decreased if elements are added or removed.

Creating an Array List

Before using Array List, we need to import the java.util. Array List package first.

ArrayList<Type> arrayList= new ArrayList<>();

Here, Type indicates the type of an arraylist. For example,

ArrayList<Integer> arrayList = new ArrayList<>();

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

we have used Integer not int. It is because we cannot use primitive types while creating an arraylist. Instead, we
have to use the corresponding wrapper classes.

Basic Operations on ArrayList

The ArrayList class provides various methods to perform different operations on arraylists.

1. Add elements
2. Access elements
3. Change elements
4. Remove elements

1. Add Elements to an ArrayList

To add a single element to the arraylist, we use the add() method of the ArrayList class.

import java.util.ArrayList;
class Main

public static void main(String[] args){

ArrayList<String> languages = new ArrayList< >(); // create ArrayList

languages.add("Java"); // add() method without the index parameter

languages.add("C");

languages.add("Python");

System.out.println("ArrayList: " + languages);

Output

ArrayList: [Java, C, Python]

In the above example, we have created an ArrayList named languages.

Here, we have used the add() method to add elements to the arraylist.

2. Access ArrayList Elements

To access an element from the arraylist, we use the get() method of the ArrayList class.

import java.util.ArrayList;

class Main

public static void main(String[] args)

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

animals.add("Cat"); // add elements in the arraylist

animals.add("Dog");

animals.add("Cow");

System.out.println("ArrayList: " + animals);

String str = animals.get(1); // get the element from the arraylist

System.out.print("Element at index 1: " + str);

}
}

Output

ArrayList: [Cat, Dog, Cow]

Element at index 1: Dog

3. Change ArrayList Elements

To change elements of the arraylist, we use the set() method of the ArrayList class.

import java.util.ArrayList;

class Main

public static void main(String[] args)

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

// add elements in the array list

languages.add("Java");

languages.add("Kotlin");

languages.add("C++");

System.out.println("ArrayList: " + languages);

// change the element of the array list

languages.set(2, "JavaScript");

System.out.println("Modified ArrayList: " + languages);

Output

ArrayList: [Java, Kotlin, C++]

Modified ArrayList: [Java, Kotlin, JavaScript]

4. Remove ArrayList Elements

To remove an element from the arraylist, we can use the remove() method of the ArrayList class.

import java.util.ArrayList;
class Main

public static void main(String[] args)

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

// add elements in the array list

animals.add("Dog");

animals.add("Cat");

animals.add("Horse");

System.out.println("ArrayList: " + animals);

// remove element from index 2

String str = animals.remove(2);

System.out.println("Updated ArrayList: " + animals);

System.out.println("Removed Element: " + str);

}}

Output

ArrayList: [Dog, Cat, Horse]

Updated ArrayList: [Dog, Cat]

Removed Element: Horse

Methods of ArrayList Class

Methods Descriptions

size() Returns the length of the arraylist.

sort() Sort the arraylist elements.

clone() Creates a new arraylist with the same element, size, and capacity.

contains() Searches the arraylist for the specified element and returns a boolean result.

ensureCapacity() Specifies the total element the arraylist can contain.

isEmpty() Checks if the arraylist is empty.

indexOf() Searches a specified element in an arraylist and returns the index of the element.
LinkedList

 The LinkedList class is a part of java collection framework.


 It is available inside the java.util package.
 The LinkedList class extends AbstractSequentialList class and implements List and Deque interface.
 Linked List is a linear data structure where the elements are called as nodes.
 The LinkedList allows to store duplicate data values.
 The LinkedList maintains the order of insertion.

Each element in a linked list is known as a node. It consists of 3 fields:

Prev - stores an address of the previous element in the list. It is null for the first element

Next - stores an address of the next element in the list. It is null for the last element

Data - stores the actual data

Creating a Java LinkedList

LinkedList<Type> linkedList = new LinkedList<>();

Here, Type indicates the type of a linked list.

LinkedList<Integer> linkedList = new LinkedList<>(); // create Integer type linked list

LinkedList<String> linkedList = new LinkedList<>(); // create String type linked list

Example:

import java.util.LinkedList;

class Main

public static void main(String[] args)

LinkedList<String> animals = new LinkedList<>(); // create linkedlist

animals.add("Dog"); // Add elements to LinkedList

animals.add("Cat");

animals.add("Cow");

System.out.println("LinkedList: " + animals);


}

Methods of Java LinkedList

LinkedList provides various methods that allow us to perform different operations in linked lists.

1. Add elements to a LinkedList

We can use the add() method to add an element (node) at the end of the LinkedList.

import java.util.LinkedList;

class Main {

public static void main(String[] args){

// create linkedlist

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

// add() method without the index parameter

animals.add("Dog");

animals.add("Cat");

animals.add("Cow");

System.out.println("LinkedList: " + animals);

// add() method with the index parameter

animals.add(1, "Horse");

System.out.println("Updated LinkedList: " + animals);

Output

LinkedList: [Dog, Cat, Cow]

Updated LinkedList: [Dog, Horse, Cat, Cow]

2. Access LinkedList elements

The get() method of the LinkedList class is used to access an element from the LinkedList.

import java.util.LinkedList;

class Main
{

public static void main(String[] args)

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

// add elements in the linked list

languages.add("Python");

languages.add("Java");

languages.add("JavaScript");

System.out.println("LinkedList: " + languages);

// get the element from the linked list

String str = languages.get(1);

System.out.print("Element at index 1: " + str);

Output

LinkedList: [Python, Java, JavaScript]

Element at index 1: Java

3. Change Elements of a LinkedList

The set() method of LinkedList class is used to change elements of the LinkedList.

import java.util.LinkedList;

class Main {

public static void main(String[] args) {

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

// add elements in the linked list

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

languages.add("Java");

System.out.println("LinkedList: " + languages);


// change elements at index 3

languages.set(3, "Kotlin");

System.out.println("Updated LinkedList: " + languages);

}}

Output

LinkedList: [Java, Python, JavaScript, Java]

Updated LinkedList: [Java, Python, JavaScript, Kotlin]

4. Remove element from a LinkedList

The remove() method of the LinkedList class is used to remove an element from the LinkedList.

import java.util.LinkedList;

class Main

public static void main(String[] args)

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

// add elements in LinkedList

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

languages.add("Kotlin");

System.out.println("LinkedList: " + languages);

// remove elements from index 1

String str = languages.remove(1);

System.out.println("Removed Element: " + str);

System.out.println("Updated LinkedList: " + languages);

VECTOR CLASS IN JAVA

 The Vector is a class in the java.util package.


 The Vector implements List interface.
 The Vector is a legacy class.
 The Vector is synchronized.
 Vector is synchronised. It means only one thread at a time can access the code.

Creating a Vector

Vector<Type> vector = new Vector< >();

Add Elements to Vector

add(element) - adds an element to vectors

add(index, element) - adds an element to the specified position

addAll(vector) - adds all elements of a vector to another vector

Example:

import java.util.Vector;

class Main {

public static void main(String[] args) {

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

// Using the add() method

mammals.add("Dog");

mammals.add("Horse");

// Using index number

mammals.add(2, "Cat");

System.out.println("Vector: " + mammals);

// Using addAll()

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

animals.add("Crocodile");

animals.addAll(mammals);

System.out.println("New Vector: " + animals);

Output

Vector: [Dog, Horse, Cat]

New Vector: [Crocodile, Dog, Horse, Cat]


Access Vector Elements

get(index) - returns an element specified by the index

iterator() - returns an iterator object to sequentially access vector elements

Example:

import java.util.Iterator;

import java.util.Vector;

class Main {

public static void main(String[] args) {

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

animals.add("Dog");

animals.add("Horse");

animals.add("Cat");

// Using get()

String element = animals.get(2);

System.out.println("Element at index 2: " + element);

// Using iterator()

Iterator<String> iterate = animals.iterator();

System.out.print("Vector: ");

while(iterate.hasNext()) {

System.out.print(iterate.next());

System.out.print(", ");

Output

Element at index 2: Cat

Vector: Dog, Horse, Cat,

Remove Vector Elements


remove(index) - removes an element from specified position

removeAll() - removes all the elements

clear() - removes all elements. It is more efficient than removeAll()

Example:

import java.util.Vector;

class Main {

public static void main(String[] args) {

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

animals.add("Dog");

animals.add("Horse");

animals.add("Cat");

System.out.println("Initial Vector: " + animals);

// Using remove()

String element = animals.remove(1);

System.out.println("Removed Element: " + element);

System.out.println("New Vector: " + animals);

// Using clear()

animals.clear();

System.out.println("Vector after clear(): " + animals);

Output

Initial Vector: [Dog, Horse, Cat]

Removed Element: Horse

New Vector: [Dog, Cat]

Vector after clear(): []

JAVA STACK CLASS

 Stack class extends the Vector class and it is its subclass.


 It works on the principle of Last-In, First-Out.
 In order to put an object on the top of the stack, we call the push() method.
 To remove and return the top element in the stack, we call pop() method.
 There are other methods like peek(), search() and empty() which are used to perform operations on the
stack.

Creating a Stack

In order to create a stack, we must import the java.util.Stack package first.

Stack<Type> stacks = new Stack<>();

Here, Type indicates the stack's type. For example,

// Create Integer type stack

Stack<Integer> stacks = new Stack<>();

// Create String type stack

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

Stack Methods

Since Stack extends the Vector class, it inherits all the methods Vector.

i) push() Method

To add an element to the top of the stack, we use the push() method.

import java.util.Stack;

class Main {

public static void main(String[] args) {

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

// Add elements to Stack

animals.push("Dog");

animals.push("Horse");
animals.push("Cat");

System.out.println("Stack: " + animals);

Output

Stack: [Dog, Horse, Cat]

ii) pop() Method

To remove an element from the top of the stack, we use the pop() method.

import java.util.Stack;

class Main {

public static void main(String[] args) {

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

// Add elements to Stack

animals.push("Dog");

animals.push("Horse");

animals.push("Cat");

System.out.println("Initial Stack: " + animals);

// Remove element stacks

String element = animals.pop();

System.out.println("Removed Element: " + element);

Output

Initial Stack: [Dog, Horse, Cat]

Removed Element: Cat

iii) peek() Method

The peek() method returns an object from the top of the stack.

import java.util.Stack;

class Main {
public static void main(String[] args) {

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

// Add elements to Stack

animals.push("Dog");

animals.push("Horse");

animals.push("Cat");

System.out.println("Stack: " + animals);

// Access element from the top

String element = animals.peek();

System.out.println("Element at top: " + element);

Output

Stack: [Dog, Horse, Cat]

Element at top: Cat

iv) search() Method

To search an element in the stack, we use the search() method. It returns the position of the element from
the top of the stack.

import java.util.Stack;

class Main {

public static void main(String[] args) {

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

// Add elements to Stack

animals.push("Dog");

animals.push("Horse");

animals.push("Cat");

System.out.println("Stack: " + animals);

// Search an element

int position = animals.search("Horse");

System.out.println("Position of Horse: " + position);


}

Output

Stack: [Dog, Horse, Cat]

Position of Horse: 2

v) empty() Method

To check whether a stack is empty or not, we use the empty() method.

import java.util.Stack;

class Main {

public static void main(String[] args) {

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

// Add elements to Stack

animals.push("Dog");

animals.push("Horse");

animals.push("Cat");

System.out.println("Stack: " + animals);

// Check if stack is empty

boolean result = animals.empty();

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

Output

Stack: [Dog, Horse, Cat]

Is the stack empty? false

SET INTERFACE:
It extends the Collection interface.

sets cannot contain duplicate elements.

we must import java.util.Set package in order to use Set.

SET INTERFACE CLASSES:

These classes are defined in the Collections framework and implement the Set interface.

 Hash Set
 Linked Hash Set
 Sorted Set
 Tree Set

The Set interface is also extended by these sub interfaces:

 Sorted Set
 Navigable Set

METHODS OF SET

The Set interface includes all the methods of the Collection interface. It's because Collection is a super interface
of Set.

add() - adds the specified element to the set

addAll() - adds all the elements of the specified collection to the set

iterator() - returns an iterator that can be used to access elements of the set sequentially

remove() - removes the specified element from the set

removeAll() - removes all the elements from the set that is present in another specified set

retainAll() - retains all the elements in the set that are also present in another specified set

clear() - removes all the elements from the set

size() - returns the length (number of elements) of the set

toArray() - returns an array containing all the elements of the set

contains() - returns true if the set contains the specified element

containsAll() - returns true if the set contains all the elements of the specified collection

hashCode() - returns a hash code value (address of the element in the set)

Set Operations
 Union
 Intersection
 Subset

HASHSET

The HashSet class is a part of java collection framework.

It is available inside the java.util package.

The HashSet class implements Set interface.

The HashSet does not maintains the order of insertion.

The elements of HashSet are organized using a mechanism called hashing.

The HashSet is used to create hash table for storing set of elements.

The HashSet initial capacity is 16 elements.

The HashSet is best suitable for search operations.

Creating a HashSet

In order to create a hash set, we must import the java.util.HashSet package first.

Once we import the package, here is how we can create hash sets in Java.

// HashSet with 8 capacity and 0.75 load factor

HashSet<Integer> numbers = new HashSet<>(8, 0.75);

capacity - The capacity of this hash set is 8.

loadFactor - The load factor of this hash set is 0.6. whenever our hash set is filled by 60%, the elements are
moved to a new hash table of double the size of the original hash table.

Methods of HashSet
The HashSet class provides various methods that allow us to perform various operations on the set.

Insert Elements to HashSet

add() - inserts the specified element to the set

addAll() - inserts all the elements of the specified collection to the set

import java.util.HashSet;

class Main

public static void main(String[] args)

HashSet<Integer> evenNumber = new HashSet<>();

// Using add() method

evenNumber.add(2);

evenNumber.add(4);

evenNumber.add(6);

System.out.println("HashSet: " + evenNumber);

HashSet<Integer> numbers = new HashSet<>();

// Using addAll() method

numbers.addAll(evenNumber);

numbers.add(5);

System.out.println("New HashSet: " + numbers);

}}

Output

HashSet: [2, 4, 6]

New HashSet: [2, 4, 5, 6]

Access HashSet Elements

To access the elements of a hash set, we can use the iterator() method. In order to use this method, we
must import the java.util.Iterator package.

import java.util.HashSet;

import java.util.Iterator;
class Main

public static void main(String[] args)

HashSet<Integer> numbers = new HashSet<>();

numbers.add(2);

numbers.add(5);

numbers.add(6);

System.out.println("HashSet: " + numbers);

// Calling iterator() method

Iterator<Integer> iterate = numbers.iterator();

System.out.print("HashSet using Iterator: ");

// Accessing elements

while(iterate.hasNext()) {

System.out.print(iterate.next());

System.out.print(", ");

} }}

Output

HashSet: [2, 5, 6]

HashSet using Iterator: 2, 5, 6,

Remove Elements

remove() - removes the specified element from the set

removeAll() - removes all the elements from the set

import java.util.HashSet;

class Main

public static void main(String[] args)

HashSet<Integer> numbers = new HashSet<>();


numbers.add(2);

numbers.add(5);

numbers.add(6);

System.out.println("HashSet: " + numbers);

// Using remove() method

boolean value1 = numbers.remove(5);

System.out.println("Is 5 removed? " + value1);

boolean value2 = numbers.removeAll(numbers);

System.out.println("Are all elements removed? " + value2);

}}

Output

HashSet: [2, 5, 6]

Is 5 removed? true

Are all elements removed? True

TREESET CLASS

The TreeSet class is a part of java collection framework.

It is available inside the java.util package.

The elements of TreeSet are organized using a mechanism called tree.

The TreeSet does not allows to store duplicate data values, but null values are allowed.

he TreeSet initial capacity is 16 elements.

The TreeSet is best suitable for search operations.

Creating a TreeSet

In order to create a tree set, we must import the java.util.TreeSet package first.

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

We have created a TreeSet without any arguments.

The elements in TreeSet are sorted ascending order

Methods of Tree Set:

The TreeSet class provides various methods that allow us to perform various operations on the set.
Insert Elements to TreeSet

add() - inserts the specified element to the set

addAll() - inserts all the elements of the specified collection to the set

import java.util.TreeSet;

class Main

public static void main(String[] args)

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

// Using the add() method

evenNumbers.add(2);

evenNumbers.add(4);

evenNumbers.add(6);

System.out.println("TreeSet: " + evenNumbers);

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

numbers.add(1);

// Using the addAll() method

numbers.addAll(evenNumbers);

System.out.println("New TreeSet: " + numbers);

}}

Output

TreeSet: [2, 4, 6]

New TreeSet: [1, 2, 4, 6]

Access TreeSet Elements

To access the elements of a tree set, we can use the iterator() method. In order to use this method, we
must import java.util.Iterator package. For example,

import java.util.TreeSet;

import java.util.Iterator;

class Main
{

public static void main(String[] args)

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

numbers.add(2);

numbers.add(5);

numbers.add(6);

System.out.println("TreeSet: " + numbers);

// Calling iterator() method

Iterator<Integer> iterate = numbers.iterator();

System.out.print("TreeSet using Iterator: ");

// Accessing elements

while(iterate.hasNext()) {

System.out.print(iterate.next());

System.out.print(", ");

} }}

Output

TreeSet: [2, 5, 6]

TreeSet using Iterator: 2, 5, 6,

Remove Elements

remove() - removes the specified element from the set

removeAll() - removes all the elements from the set

import java.util.TreeSet;

class Main

public static void main(String[] args)

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

numbers.add(2);
numbers.add(5);

numbers.add(6);

System.out.println("TreeSet: " + numbers);

// Using the remove() method

boolean value1 = numbers.remove(5);

System.out.println("Is 5 removed? " + value1);

// Using the removeAll() method

boolean value2 = numbers.removeAll(numbers);

System.out.println("Are all elements removed? " + value2);

Output

TreeSet: [2, 5, 6]

Is 5 removed? true

Are all elements removed? true

QUEUE INTERFACE

 The Queue interface is a child interface of the Collection interface.


 The Queue interface is available inside the java.util package.
 The Queue interface allows duplicate elements.
 The Queue interface preserves the order of insertion.
 It defines the methods that are commonly used by classes like PriorityQueue and ArrayDeque.

Methods of Queue

add() - Inserts the specified element into the queue.

offer() - Inserts the specified element into the queue.returns true on success and false on failure.

element() - Returns the head of the queue.

peek() - Returns the head of the queue. Returns null if the queue is empty.

remove() - Returns and removes the head of the queue.

poll() - Returns and removes the head of the queue. Returns null if the queue is empty.

Classes that Implement Queue


ArrayDeque
LinkedList
PriorityQueue

Creating queue objects:


Queue<obj> queue = new PriorityQueue<obj>();

Implementation of the Queue Interface

Implementing the LinkedList Class

import java.util.Queue;

import java.util.LinkedList;

class Main {

public static void main(String[] args)

// Creating Queue using the LinkedList class

Queue<Integer> numbers = new LinkedList<>();

// offer elements to the Queue

numbers.offer(1);

numbers.offer(2);

numbers.offer(3);

System.out.println("Queue: " + numbers);

// Access elements of the Queue

int accessedNumber = numbers.peek();

System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue

int removedNumber = numbers.poll();

System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);

}}

Output
Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]
PRIORITYQUEUE

The PriorityQueue class provides the functionality of the heap data structure.

The PriorityQueue is a child class of AbstractQueue

The PriorityQueue allows to store duplicate data values, but not null values.

The PriorityQueue maintains the order of insertion.

The PriorityQueue used priority heap to organize its elements.

Creating PriorityQueue

To create a priority queue, we must import the java.util.PriorityQueue package.

PriorityQueue<Integer> numbers = new PriorityQueue<>();

We have created a priority queue without any arguments.

The head of the priority queue is the smallest element of the queue. And elements are removed in ascending order
from the queue.

Methods of PriorityQueue

 Insert Elements to PriorityQueue


 Access PriorityQueue Elements
 Remove PriorityQueue Elements
 Iterating Over a PriorityQueue

2. Implementing the PriorityQueue Class


import java.util.Queue;

import java.util.PriorityQueue;

class Main

public static void main(String[] args)


{

// Creating Queue using the PriorityQueue class

Queue<Integer> numbers = new PriorityQueue<>();

// offer elements to the Queue

numbers.offer(5);

numbers.offer(1);

numbers.offer(2);

System.out.println("Queue: " + numbers);

// Access elements of the Queue

int accessedNumber = numbers.peek();

System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue

int removedNumber = numbers.poll();

System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);

}}

Output

Queue: [1, 5, 2]

Accessed Element: 1

Removed Element: 1

Updated Queue: [2, 5]

ARRAY DEQUE
Deque stands for Double-Ended Queue. A Queue is a simple, linear data structure that allows us to insert
elements from one end and remove them from another end.

The ArrayDeque class in Java provides a dynamic array that can be used as a Deque. This class implements the
Deque and the Queue interface.

It uses two pointers called head and tail. The head takes care of insertion and deletion from the front, and the tail
takes care of insertion and deletion from the end.

If an element is added at the front, then the head moves forward(from left to right). If an element is removed from
the front then the head moves backward.

If an element is added at the end, then the tail moves from right to left. If an element is removed from the end,
then the tail moves forward(left to right).

The Array Deque allows to store duplicate data values, but not null values.

The Array Deque maintains the order of insertion.

The Array Deque is faster than Linked List and Stack.

Creating Array Deque

In order to create an array deque, we must import the java.util.ArrayDeque package.

ArrayDeque<Type> animal = new ArrayDeque<>();

Here, Type indicates the type of the array deque.

// Creating String type ArrayDeque

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

// Creating Integer type ArrayDeque

ArrayDeque<Integer> age = new ArrayDeque<>();

Methods of ArrayDeque

The ArrayDeque class provides implementations for all the methods present in Queue and Deque interface.

Insertion (Adding Elements to ArrayDeque)

We can insert elements at the front or the rear of the Deque.


ArrayDeque provides the offerFirst() and addFirst() methods to add elements at the front of the ArrayDeque.

We can use the offerLast() or the addLast() methods to insert elements at the rear of the ArrayDeque.

import java.util.ArrayDeque;

import java.util.Deque;

public class ArrayDequeDemo

public static void main(String[] args)

Deque<Integer> deck = new ArrayDeque<Integer>();

deck.addFirst(5);

deck.addFirst(10);

System.out.println("Deque After Inserting using addFirst(): " + deck);

deck.offerFirst(15);

deck.offerFirst(20);

System.out.println("Deque After Inserting using offerFirst(): " + deck);

}}

Output:

Deque After Inserting using addFirst(): [10, 5]


Deque After Inserting using offerFirst(): [20, 15, 10, 5]

import java.util.ArrayDeque;

import java.util.Deque;

public class ArrayDequeDemo

public static void main(String[] args)

Deque<Integer> deck = new ArrayDeque<Integer>();

deck.addLast(5);
deck.addLast(10);

System.out.println("Deque After Inserting using addLast(): " + deck);

deck.offerLast(15);

deck.offerLast(20);

System.out.println("Deque After Inserting using offerLast(): " + deck);

}}

2. Access elements using peek(), peekFirst() and peekLast() method

peek() - returns the first element of the array deque

peekFirst() - returns the first element of the array deque (equivalent to peek())

peekLast() - returns the last element of the array deque

import java.util.ArrayDeque;

class Main {

public static void main(String[] args) {

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

animals.add("Dog");

animals.add("Cat");

animals.add("Horse");

System.out.println("ArrayDeque: " + animals);

// Using peek()

String element = animals.peek();

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

// Using peekFirst()

String firstElement = animals.peekFirst();

System.out.println("First Element: " + firstElement);

// Using peekLast

String lastElement = animals.peekLast();

System.out.println("Last Element: " + lastElement);

}}
Output

ArrayDeque: [Dog, Cat, Horse]

Head Element: Dog

First Element: Dog

Last Element: Horse

Deletion (Deleting Elements from ArrayDeque)

We have the pollFirst() and the removeFirst() methods that can remove elements from the front of the
ArrayDeque that return the element present at the head or the front of the Deque.

Similarly, the pollLast() and the removeLast() methods are used to remove the last element of the Deque.

import java.util.ArrayDeque;

import java.util.Deque;

public class ArrayDequeDemo

public static void main(String[] args)

Deque<Integer> deck = new ArrayDeque<Integer>();

deck.addLast(5);

deck.addLast(10);

deck.addLast(15);

deck.addLast(20);

System.out.println("Deque After Insertion: " + deck);

Integer i1 = deck.removeLast();

System.out.println("Deleted Element: " + i1);

System.out.println("Deque after Deletion: " + deck);

Integer i2 = deck.pollLast();

System.out.println("Deleted Element: " + i2);

System.out.println("Deque after Deletion: " + deck);

}}

Output:

Deque After Insertion: [5, 10, 15, 20]


Deleted Element: 20
Deque after Deletion: [5, 10, 15]
Deleted Element: 15
Deque after Deletion: [5, 10]

3. Remove Element: using the clear() method

To remove all the elements from the array deque, we use the clear() method.

import java.util.ArrayDeque;

class Main

public static void main(String[] args)

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

animals.add("Dog");

animals.add("Cat");

animals.add("Horse");

System.out.println("ArrayDeque: " + animals);

// Using clear()

animals.clear();

System.out.println("New ArrayDeque: " + animals);

}}

Iterating the ArrayDeque

iterator() - returns an iterator that can be used to iterate over the array deque

descendingIterator() - returns an iterator that can be used to iterate over the array deque in reverse order

In order to use these methods, we must import the java.util.Iterator package.

import java.util.ArrayDeque;

import java.util.Iterator;

class Main {

public static void main(String[] args) {

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

animals.add("Dog");
animals.add("Cat");

animals.add("Horse");

System.out.print("ArrayDeque: ");

// Using iterator()

Iterator<String> iterate = animals.iterator();

while(iterate.hasNext()) {

System.out.print(iterate.next());

System.out.print(", ");

System.out.print("\nArrayDeque in reverse order: ");

// Using descendingIterator()

Iterator<String> desIterate = animals.descendingIterator();

while(desIterate.hasNext()) {

System.out.print(desIterate.next());

System.out.print(", ");

} }}

Output

ArrayDeque: [Dog, Cat, Horse]

ArrayDeque in reverse order: [Horse, Cat, Dog]

MAP INTERFACE IN JAVA

The Map interface of the Java collections framework provides the functionality of the map data structure.

The Map stores the elements as a pair of key and value.

The Map does not allows duplicate keys, but allows duplicate values.

In a Map, each key can map to at most one value only.


The Map interface maintains 3 different sets:

The set of keys

The set of values

The set of key/value associations (mapping).

Classes that implement Map

These classes are defined in the collections framework and implement the Map interface.

Map is an interface, we cannot create objects from it.

 HashMap
 EnumMap
 LinkedHashMap
 WeakHashMap
 TreeMap

Interfaces that extend Map

The Map interface is also extended by these subinterfaces:

 SortedMap
 NavigableMap
MAP INTERFACE METHODS

The Map interface includes all the methods of the Collection interface. It is because Collection is a super interface
of Map.

put(K, V) - Inserts the association of a key K and a value V into the map. If the key is already present, the new
value replaces the old value.

putAll() - Inserts all the entries from the specified map to this map.

get(K) - Returns the value associated with the specified key K. If the key is not found, it returns null

containsKey(K) - Checks if the specified key K is present in the map or not.

containsValue(V) - Checks if the specified value V is present in the map or not.

replace(K, V) - Replace the value of the key K with the new specified value V.

replace(K, oldValue, newValue) - Replaces the value of the key K with the new value newValue only if the
key K is associated with the value oldValue.

remove(K) - Removes the entry from the map represented by the key K.

remove(K, V) - Removes the entry from the map that has key K associated with value V.

keySet() - Returns a set of all the keys present in a map.

values() - Returns a set of all the values present in a map.

entrySet() - Returns a set of all the key/value mapping present in a map.

HashMap

The HashMap class implements the Map interface.

The HashMap class of the Java collections framework provides the functionality of the hash table data structure.

It stores elements in key/value pairs. Here, keys are unique identifiers used to associate each value on a map.

Create a HashMap

In order to create a hash map, we must import the java.util.HashMap package first.

// hashMap creation with 8 capacity and 0.6 load factor

HashMap<K, V> numbers = new HashMap<>();

In the above code, we have created a hashmap named numbers. Here, K represents the key type and V represents
the type of values. For example,
HashMap<String, Integer> numbers = new HashMap<>();

Here, the type of keys is String and the type of values is Integer.

import java.util.HashMap;

class Main {

public static void main(String[] args) {

// create a hashmap

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

// add elements to hashmap

languages.put("Java", 8);

languages.put("JavaScript", 1);

languages.put("Python", 3);

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

}}

Output

HashMap: {Java=8, JavaScript=1, Python=3}

In the above example, we have created a HashMap named languages.

Here, we have used the put() method to add elements to the hashmap.

Basic Operations on Java HashMap

The HashMap class provides various methods to perform different operations on hashmaps.

 Add elements
 Access elements
 Change elements
 Remove elements

1. Add elements to a HashMap

To add a single element to the hashmap, we use the put() method of the HashMap class.

import java.util.HashMap;

class Main {

public static void main(String[] args) {

// create a hashmap

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


System.out.println("Initial HashMap: " + numbers);

// put() method to add elements

numbers.put("One", 1);

numbers.put("Two", 2);

numbers.put("Three", 3);

System.out.println("HashMap after put(): " + numbers);

}}

Output

Initial HashMap: {}

HashMap after put(): {One=1, Two=2, Three=3}

Here, we are passing the String value One as the key and Integer value 1 as the value to the put() method.

2. Access HashMap Elements

We can use the get() method to access the value from the hashmap.

import java.util.HashMap;

class Main

public static void main(String[] args)

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

languages.put(1, "Java");

languages.put(2, "Python");

languages.put(3, "JavaScript");

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

// get() method to get value

String value = languages.get(1);

System.out.println("Value at index 1: " + value);

}}

Output

HashMap: {1=Java, 2=Python, 3=JavaScript}


Value at index 1: Java

3. Change HashMap Value

We can use the replace() method to change the value associated with a key in a hashmap.

import java.util.HashMap;

class Main {

public static void main(String[] args) {

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

languages.put(1, "Java");

languages.put(2, "Python");

languages.put(3, "JavaScript");

System.out.println("Original HashMap: " + languages);

// change element with key 2

languages.replace(2, "C++");

System.out.println("HashMap using replace(): " + languages);

}}

Output:

Original HashMap: {1=Java, 2=Python, 3=JavaScript}

HashMap using replace(): {1=Java, 2=C++, 3=JavaScript}

4. Remove HashMap Elements

To remove elements from a hashmap, we can use the remove() method.

import java.util.HashMap;

class Main {

public static void main(String[] args) {

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

languages.put(1, "Java");

languages.put(2, "Python");

languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);

// remove element associated with key 2

String value = languages.remove(2);

System.out.println("Removed value: " + value);

System.out.println("Updated HashMap: " + languages);

}}

Output:

HashMap: {1=Java, 2=Python, 3=JavaScript}

Removed value: Python

Updated HashMap: {1=Java, 3=JavaScript}

JAVA ENUMMAP

The EnumMap class of the Java collections framework provides a map implementation for elements of an enum.

In EnumMap, enum elements are used as keys. It implements the Map interface.

Creating an EnumMap

In order to create an enum map, we must import the java.util.EnumMap package first.

enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE

EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);

we have created an enum map named sizes.

Here,

Size - keys of the enum that map to values

Integer - values of the enum map associated with the corresponding keys

Methods of EnumMap

The EnumMap class provides methods that allow us to perform various elements on the enum maps.

Insert Elements to EnumMap

put() - inserts the specified key/value mapping (entry) to the enum map
putAll() - inserts all the entries of a specified map to this map

import java.util.EnumMap;

class Main {

enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE

public static void main(String[] args) {

// Creating an EnumMap of the Size enum

EnumMap<Size, Integer> sizes1 = new EnumMap<>(Size.class);

// Using the put() Method

sizes1.put(Size.SMALL, 28);

sizes1.put(Size.MEDIUM, 32);

System.out.println("EnumMap1: " + sizes1);

EnumMap<Size, Integer> sizes2 = new EnumMap<>(Size.class);

// Using the putAll() Method

sizes2.putAll(sizes1);

sizes2.put(Size.LARGE, 36);

System.out.println("EnumMap2: " + sizes2);

}}

Output

EnumMap1: {SMALL=28, MEDIUM=32}

EnumMap2: {SMALL=28, MEDIUM=32, LARGE=36}

In the above example, we have used the putAll() method to insert all the elements of an enum map sizes1 to an
enum map of sizes2.

Access EnumMap Elements

1. Using entrySet(), keySet() and values()

entrySet() - returns a set of all the keys/values mapping (entry) of an enum map

keySet() - returns a set of all the keys of an enum map

values() - returns a set of all the values of an enum map


import java.util.EnumMap;

class Main {

enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE

public static void main(String[] args) {

// Creating an EnumMap of the Size enum

EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);

sizes.put(Size.SMALL, 28);

sizes.put(Size.MEDIUM, 32);

sizes.put(Size.LARGE, 36);

sizes.put(Size.EXTRALARGE, 40);

System.out.println("EnumMap: " + sizes);

// Using the entrySet() Method

System.out.println("Key/Value mappings: " + sizes.entrySet());

// Using the keySet() Method

System.out.println("Keys: " + sizes.keySet());

// Using the values() Method

System.out.println("Values: " + sizes.values());

}}

Output

EnumMap: {SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40}

Key/Value mappings: [SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40]

Keys: [SMALL, MEDIUM, LARGE, EXTRALARGE]

Values: [28, 32, 36, 40]

2. Using the get() Method

The get() method returns the value associated with the specified key. It returns null if the specified key is not
found.

import java.util.EnumMap;

class Main {
enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE

public static void main(String[] args) {

// Creating an EnumMap of the Size enum

EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);

sizes.put(Size.SMALL, 28);

sizes.put(Size.MEDIUM, 32);

sizes.put(Size.LARGE, 36);

sizes.put(Size.EXTRALARGE, 40);

System.out.println("EnumMap: " + sizes);

// Using the get() Method

int value = sizes.get(Size.MEDIUM);

System.out.println("Value of MEDIUM: " + value);

}}

Output

EnumMap: {SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40}

Value of MEDIUM: 32

Remove EnumMap Elements

remove(key) - returns and removes the entry associated with the specified key from the map

remove(key, value) - removes the entry from the map only if the specified key mapped to the specified value and
return a boolean value

import java.util.EnumMap;

class Main {

enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE

public static void main(String[] args) {

// Creating an EnumMap of the Size enum

EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);


sizes.put(Size.SMALL, 28);

sizes.put(Size.MEDIUM, 32);

sizes.put(Size.LARGE, 36);

sizes.put(Size.EXTRALARGE, 40);

System.out.println("EnumMap: " + sizes);

// Using the remove() Method

int value = sizes.remove(Size.MEDIUM);

System.out.println("Removed Value: " + value);

boolean result = sizes.remove(Size.SMALL, 28);

System.out.println("Is the entry {SMALL=28} removed? " + result);

System.out.println("Updated EnumMap: " + sizes);

}}

Output

EnumMap: {SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40}

Removed Value: 32

Is the entry {SMALL=28} removed? True

Updated EnumMap: {LARGE=36, EXTRALARGE=40}

JAVA TREEMAP

The TreeMap class that implements treemap in Java is a part of java.util package. It implements the Map
interface.

The TreeMap class extends AbstractMap class and also implements the NavigableMap and SortedMap
(indirectly) interface.

TreeMap is not synchronized.

By default, TreeMap elements are in ascending order by default.

TreeMap does not allow duplicate elements.

TreeMap allows null values but not null keys.


Creating a TreeMap

In order to create a TreeMap, we must import the java.util.TreeMap package first.

TreeMap<Key, Value> numbers = new TreeMap<>();

we have created a TreeMap named numbers without any arguments. In this case, the elements in TreeMap are
sorted naturally (ascending order).

we can customize the sorting of elements by using the Comparator interface.

Key - a unique identifier used to associate each element (value) in a map

Value - elements associated by keys in a map

Methods of TreeMap

The TreeMap class provides various methods that allow us to perform operations on the map.

Insert Elements to TreeMap

put() - inserts the specified key/value mapping (entry) to the map

putAll() - inserts all the entries from specified map to this map

putIfAbsent() - inserts the specified key/value mapping to the map if the specified key is not present in the map

import java.util.TreeMap;

class Main {

public static void main(String[] args) {

// Creating TreeMap of even numbers

TreeMap<String, Integer> evenNumbers = new TreeMap<>();

// Using put()
evenNumbers.put("Two", 2);

evenNumbers.put("Four", 4);

// Using putIfAbsent()

evenNumbers.putIfAbsent("Six", 6);

System.out.println("TreeMap of even numbers: " + evenNumbers);

//Creating TreeMap of numbers

TreeMap<String, Integer> numbers = new TreeMap<>();

numbers.put("One", 1);

// Using putAll()

numbers.putAll(evenNumbers);

System.out.println("TreeMap of numbers: " + numbers);

}}

Output

TreeMap of even numbers: {Four=4, Six=6, Two=2}

TreeMap of numbers: {Four=4, One=1, Six=6, Two=2}

Access TreeMap Elements

1. Using entrySet(), keySet() and values()

entrySet() - returns a set of all the key/values mapping (entry) of a treemap

keySet() - returns a set of all the keys of a tree map

values() - returns a set of all the maps of a tree map

import java.util.TreeMap;

class Main {

public static void main(String[] args) {

TreeMap<String, Integer> numbers = new TreeMap<>();

numbers.put("One", 1);

numbers.put("Two", 2);

numbers.put("Three", 3);

System.out.println("TreeMap: " + numbers);

// Using entrySet()
System.out.println("Key/Value mappings: " + numbers.entrySet());

// Using keySet()

System.out.println("Keys: " + numbers.keySet());

// Using values()

System.out.println("Values: " + numbers.values());

}}

Output

TreeMap: {One=1, Three=3, Two=2}

Key/Value mappings: [One=1, Three=3, Two=2]

Keys: [One, Three, Two]

Values: [1, 3, 2]

Remove TeeMap Elements

remove(key) - returns and removes the entry associated with the specified key from a TreeMap

remove(key, value) - removes the entry from the map only if the specified key is associated with the specified
value and returns a boolean value

import java.util.TreeMap;

class Main {

public static void main(String[] args) {

TreeMap<String, Integer> numbers = new TreeMap<>();

numbers.put("One", 1);

numbers.put("Two", 2);

numbers.put("Three", 3);

System.out.println("TreeMap: " + numbers);

// remove method with single parameter

int value = numbers.remove("Two");

System.out.println("Removed value: " + value);

// remove method with two parameters

boolean result = numbers.remove("Three", 3);

System.out.println("Is the entry {Three=3} removed? " + result);

System.out.println("Updated TreeMap: " + numbers);


}}

Output

TreeMap: {One=1, Three=3, Two=2}

Removed value = 2

Is the entry {Three=3} removed? True

Updated TreeMap: {One=1}

Replace TreeMap Elements

replace(key, value) - replaces the value mapped by the specified key with the new value

replace(key, old, new) - replaces the old value with the new value only if the old value is already associated with
the specified key

replaceAll(function) - replaces each value of the map with the result of the specified function

import java.util.TreeMap;

class Main {

public static void main(String[] args) {

TreeMap<String, Integer> numbers = new TreeMap<>();

numbers.put("First", 1);

numbers.put("Second", 2);

numbers.put("Third", 3);

System.out.println("Original TreeMap: " + numbers);

// Using replace()

numbers.replace("Second", 22);

numbers.replace("Third", 3, 33);

System.out.println("TreeMap using replace: " + numbers);

// Using replaceAll()

numbers.replaceAll((key, oldValue) -> oldValue + 2);

System.out.println("TreeMap using replaceAll: " + numbers);

}}
Output

Original TreeMap: {First=1, Second=2, Third=3}

TreeMap using replace(): {First=1, Second=22, Third=33}

TreeMap using replaceAll(): {First=3, Second=24, Third=35}

TreeMap Comparator

Treemap elements are sorted naturally (in ascending order). However, we can also customize the ordering
of keys.

we need to create our own comparator class based on which keys in a treemap are sorted.

import java.util.TreeMap;

import java.util.Comparator;

class Main {

public static void main(String[] args) {

// Creating a treemap with a customized comparator

TreeMap<String, Integer> numbers = new TreeMap<>(new CustomComparator());

numbers.put("First", 1);

numbers.put("Second", 2);

numbers.put("Third", 3);

numbers.put("Fourth", 4);

System.out.println("TreeMap: " + numbers);

// Creating a comparator class

public static class CustomComparator implements Comparator<String> {

@Override

public int compare(String number1, String number2) {

int value = number1.compareTo(number2);

// elements are sorted in reverse order

if (value > 0) {
return -1;

else if (value < 0) {

return 1;

else {

return 0;

}} }}

Output

TreeMap: {Third=3, Second=2, Fourth=4, First=1}

COLLECTION ALGORITHMS IN JAVA

The Java collections framework provides various algorithms that can be used to manipulate elements stored in
data structures.

Algorithms in Java are static methods that can be used to perform various operations on collections.

All the collection algorithms in the java are defined in a class called Collections which defined in
the java.util package.

All these algorithms are highly efficient and make coding very easy. It is better to use them than trying to re-
implement them.

Since algorithms can be used on various collections, these are also known as generic algorithms.

Method Description

void sort(List list) Sorts the elements of the list as determined by


their natural ordering.

void sort(List list, Comparator comp) Sorts the elements of the list as determined by
Comparator comp.

void reverse(List list) Reverses all the elements sequence in list.

void rotate(List list, int n) Rotates list by n places to the right. To rotate
left, use a negative value for n.
Method Description

void shuffle(List list) Shuffles the elements in list.

void shuffle(List list, Random r) Shuffles the elements in the list by using r as a
source of random numbers.

void copy(List list1, List list2) Copies the elements of list2 to list1.

void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices
specified by idx1 and idx2.

int binarySearch(List list, Object value) Returns the position of value in the list (must be
in the sorted order), or -1 if value is not found.

Object max(Collection c) Returns the largest element from the collection c


as determined by natural ordering.

Object max(Collection c, Comparator Returns the largest element from the collection c
comp) as determined by Comparator comp.

Object min(Collection c) Returns the smallest element from the collection


c as determined by natural ordering.

Object min(Collection c, Comparator Returns the smallest element from the collection
comp) c as determined by Comparator comp.

void fill(List list, Object obj) Assigns obj to each element of the list.

Enumeration enumeration(Collection c) Returns an enumeration over Collection c.

ArrayList list(Enumeration enum) Returns an ArrayList that contains the elements


of enum.

Set singleton(Object obj) Returns obj as an immutable set.

List singletonList(Object obj) Returns obj as an immutable list.


Method Description

Map singletonMap(Object k, Object v) Returns the key(k)/value(v) pair as an immutable


map.

Collection Returns a thread-safe collection backed by c.


synchronizedCollection(Collection c)

List synchronizedList(List list) Returns a thread-safe list backed by list.

Map synchronizedMap(Map m) Returns a thread-safe map backed by m.

SortedMap Returns a thread-safe SortedMap backed by sm.


synchronizedSortedMap(SortedMap sm)

Set synchronizedSet(Set s) Returns a thread-safe set backed by s.

SortedSet Returns a thread-safe set backed by ss.


synchronizedSortedSet(SortedSet ss)

Collection Returns an unmodifiable collection backed by c.


unmodifiableCollection(Collection c)

List unmodifiableList(List list) Returns an unmodifiable list backed by list.

Set unmodifiableSet(Set s) Returns an unmodifiable thread-safe set backed


by s.

Accessing a Collection

To access, modify or remove any element from any collection we need to first find the element, for which we
have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements
of any collection.

Using Iterator interface

Using ListIterator interface

Using for-each loop

Accessing elements using Iterator


Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of
the collection. Each collection classes provide iterator() method to return an iterator.

import java.util.*;

class Test_Iterator

public static void main(String[] args)

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

ar.add("ab");

ar.add("bc");

ar.add("cd");

ar.add("de");

Iterator it = ar.iterator(); //Declaring Iterator

while(it.hasNext())

System.out.print(it.next()+" ");

} }}

Output :

ab bc cd de

Accessing element using ListIterator

ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those
collections that implement the List Interface.

import java.util.*;

class Test_Iterator

public static void main(String[] args)

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

ar.add("ab");

ar.add("bc");
ar.add("cd");

ar.add("de");

ListIterator litr = ar.listIterator();

while(litr.hasNext()) //In forward direction

System.out.print(litr.next()+" ");

while(litr.hasPrevious()) //In backward direction

System.out.print(litr.next()+" ");

} }}

Output :

ab bc cd de

de cd bc ab

Using for-each loop

for-each version of for loop can also be used for traversing each element of a collection. But this can only be used
if we don't want to modify the contents of a collection and we don't want any reverse access. for-each loop can
cycle through any collection of object that implements Iterable interface.

import java.util.*;

class ForEachDemo

public static void main(String[] args)

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

ls.add("a");

ls.add("b");

ls.add("c");

ls.add("d");

for(String str : ls)

{
System.out.print(str+" ");

} }}

Output :

abcd

Comparator Interface

In Java, Comparator interface is used to order the object in your own way. It gives you ability to decide how
element are stored within sorted collection and map.

Comparator Interface defines compare() method. This method compare two object and return 0 if two object are
equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value is return. The
method can throw a ClassCastException if the type of object are not compatible for comparison.

Example

Student class

class Student

int roll;

String name;

Student(int r,String n)

roll = r;

name = n;

public String toString()

return roll+" "+name;

MyComparator class

This class defines the comparison logic for Student class based on their roll. Student object will be sotred in
ascending order of their roll.

class MyComparator implements Comparator

public int compare(Student s1,Student s2)

{
if(s1.roll == s2.roll) return 0;

else if(s1.roll > s2.roll) return 1;

else return -1;

} }

public class Test

public static void main(String[] args)

TreeSet< Student> ts = new TreeSet< Student>(new MyComparator());

ts.add(new Student(45, "Rahul"));

ts.add(new Student(11, "Adam"));

ts.add(new Student(19, "Alex"));

System.out.println(ts);

}}

Output :

[ 11 Adam, 19 Alex, 45 Rahul ]

ARRAYS CLASS IN JAVA

The java collection framework has a class Arrays that provides methods for creating dynamic array and perform
various operations like search, asList, campare, etc.

The Arrays class in java is defined in the java.util package. All the methods defined by Arrays class are static
methods.

Java Arrays Class declaration

public class Arrays extends Object

ARRAYS CLASS METHODS IN JAVA


List asList(): The asList() method returns a fixed-size list that is backed by the specified array.

int binarySearch(): The binarySearch() method is used to search the index position of an element with a specific
value.

compare(array1, array2): This method is used to compare two arrays passed as parameters lexicographically.
Both arrays array1 and array2 must have the same data types.

compareUnsigned(array1, array2): This method is used to compare two arrays lexicographically, numerically
treating elements as unsigned.

copyOf(arrayOriginal, newLength): This method was added in arrays class in Java 6 version. It returns an array
that is copy of arrayOriginal. newLength represents the length of copy.

copyOfRange(arrayOriginal, from, to): This method was also added in arrays class in Java 1.6 version. The
copyOfRange() method returns a copy of range (from one index to another) within an array.

deepEquals(): The deepEquals() method (added in arrays class in Java 5 version) returns true if the two specified
arrays are deeply equal to one another.

equals(array1, array2): The equals() method is used to check equality for one-dimensional array. It returns true
if two arrays are equivalent.

fill(array, value): The fill() method is used to fill an array with the specified value.

fill(array, from, to, value): This version of fill() method is used to assign a value to a subset of an array.

sort(array): The sort() method is used to sort the entire array in ascending order.

sort(array, from, to): This version of sort() method is used to sort elements of an array within a specific range in
ascending order.

toString(array): The toString() method is used to format elements of array in a string. Each element value is
enclosed in brackets and are separated from each other with commas.

stream(array): The stream() method was introduced in Arrays class in Java 8 version. It is used to convert an
array into a stream of corresponding data types.

stream(array, from, to): This version of stream() method is used to convert array into a stream with a specific
range.

parallelSort(array): This method is used to sort elements of an array of larger size in parallel. It can be used to
sort array of primitive types or objects.

parallelSort(array, from, to): This form of parallelSort() method is used to sort an array in a specific range.

mismatch(array1, array2): The mismatch() method finds and returns the index of the first mismatch between
two arrays.

mismatch(array1, from, to, array2, from, to): This form of mismatch() method finds and returns the relative
index of the first mismatch between two arrays over the specified range.
hashCode(array): This method returns a hash code based on the elements of the specified array.

LEGACY CLASSES - JAVA COLLECTIONS

Early version of java did not include the Collection framework. It only defined several classes and
interface that provide method for storing objects. When Collection framework were added in J2SE 1.2, the
original classes were reengineered to support the collection interface. These classes are also known as Legacy
classes. All legacy claases and interface were redesign by JDK 5 to support Generics.

The following are the legacy classes defined by java.util package.

 Dictionary
 HashTable
 Properties
 Stack
 Vector

Vector class

1. Vector is similar to ArrayList which represents a dynamic array.


2. The only difference between Vector and ArrayList is that Vector is synchronised while Array is not.

Vector class has following four constructor

 Vector()
 Vector(int size)
 Vector(int size, int incr)
 Vector(Collection< ? extends E> c)

Method Description

addElement() add element to the Vector

elementAt() return the element at specified index

elements return an enumeration of element in vector

firstElement() return first element in the Vector

lastElement() return last element in the Vector

removeAllElement() remove all element of the Vector

import java.util.*;
public class Test

public static void main(String[] args)

Vector ve = new Vector();

ve.add(10);

ve.add(20);

ve.add(30);

ve.add(40);

ve.add(50);

ve.add(60);

Enumeration en = ve.elements();

while(en.hasMoreElements())

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

} }}

Output :

10

20

30

40

50

60

HASHTABLE CLASS

Like HashMap, Hashtable also stores key/value pair in hashtable. However neither keys nor values can be null.

There is one more difference between HashMap and Hashtable that is Hashtable is synchronized while HashMap
is not.
Hashtable has following four constructor

Hashtable()

Hashtable(int size)

Hashtable(int size, float fillratio)

Hashtable(Map< ? extends K, ? extends V> m)

import java.util.*;

class HashTableDemo

public static void main(String args[])

Hashtable< String,Integer> ht = new Hashtable< String,Integer>();

ht.put("a",new Integer(100));

ht.put("b",new Integer(200));

ht.put("c",new Integer(300));

ht.put("d",new Integer(400));

Set st = ht.entrySet();

Iterator itr=st.iterator();

while(itr.hasNext())

Map.Entry m=(Map.Entry)itr.next();

System.out.println(itr.getKey()+" "+itr.getValue());

} }}

Output:

a 100

b 200

c 300
d 400

Properties class

Properties class extends Hashtable class.

It is used to maintain list of value in which both key and value are String

Properties class define two constructor

Properties()

Properties(Properties default)

import java.util.*;

public class Test

public static void main(String[] args)

Properties pr = new Properties();

pr.put("Java", "James Ghosling");

pr.put("C++", "Bjarne Stroustrup");

pr.put("C", "Dennis Ritchie");

pr.put("C#", "Microsoft Inc.");

Set< ?> creator = pr.keySet();

for(Object ob: creator)

System.out.println(ob+" was created by "+ pr.getProperty((String)ob) );

} }}

Output :

Java was created by James Ghosling

C++ was created by Bjarne Stroustrup

C was created by Dennis Ritchie

C# was created by Microsoft Inc


Stack Class:

The Stack class extends the Vector class, which has members that follow the LIFO (LAST IN
FIRST OUT) principle. The stack implementation only has one default constructor, Stack ().

import java.util.*;

class Coderz {

public static void main(String args[])

Stack stobj = new Stack();

stobj.push(10);

stobj.push(9);

stobj.push(8);

stobj.push(7);

stobj.push(6);

Enumeration eobj = stobj.elements();

while(eobj.hasMoreElements())

System.out.print(eobj.nextElement()+" ");

stobj.pop();

stobj.pop();

System.out.println("\nAfter popping out two elements");

Enumeration eobj2 = stobj.elements();

while(eobj2.hasMoreElements())

System.out.print(eobj2.nextElement()+" ");

}}

Output:

10 9 8 7 6

After popping out two elements 10 9 8

Dictionary Class:
The Dictionary class is similar to Map in that it represents the key/value storage repository. The Dictionary class
is an abstract class that holds data in the form of a key/value pair. The dictionary can be defined as a collection of
key/value pairs.

UTILITY CLASSES

StringTokenizer class

The StringTokenizer is a built-in class in java used to break a string into tokens. The StringTokenizer class is
available inside the java.util package.

The StringTokenizer class object internally maintains a current position within the string to be tokenized.

A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

The StringTokenizer class in java has the following constructor.

StringTokenizer(String str) - It creates StringTokenizer object for the specified string str with default delimeter.

StringTokenizer(String str, String delimeter) - It creates StringTokenizer object for the specified string str with
specified delimeter.

StringTokenizer(String str, String delimeter, boolean returnValue) - It creates StringTokenizer object with
specified string, delimeter and returnValue.

Methods with Description:

String nextToken() -It returns the next token from the StringTokenizer object.

String nextToken(String delimeter)- It returns the next token from the StringTokenizer object based on the
delimeter.

Object nextElement() - It returns the next token from the StringTokenizer object.

boolean hasMoreTokens() - It returns true if there are more tokens in the StringTokenizer object. otherwise
returns false.

boolean hasMoreElements() - It returns true if there are more tokens in the StringTokenizer object. otherwise
returns false.

int countTokens() - It returns total number of tokens in the StringTokenizer object.

BITSET CLASS:

 The BitSet is a built-in class in java used to create a dynamic array of bits represented by boolean values.
 The BitSet class is available inside the java.util package.
 The BitSet array can increase in size as needed. This feature makes the BitSet similar to a Vector of bits.
 The bit values can be accessed by non-negative integers as an index.
 The size of the array is flexible and can grow to accommodate additional bit as needed.
 The default value of the BitSet is boolean false with a representation as 0 (off).
 BitSet uses 1 bit of memory per each boolean value.

The BitSet class in java has the following constructor.

BitSet( ) - It creates a default BitSet object.

BitSet(int noOfBits) - It creates a BitSet object with number of bits that it can hold. All bits are initialized to
zero.

The BitSet class in java has the following methods.

void and(BitSet bitSet) - It performs AND operation on the contents of the invoking BitSet object with those
specified by bitSet.

void andNot(BitSet bitSet) - For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.

void or(BitSet bitSet) - It performs OR operation on the contents of the invoking BitSet object with those
specified by bitSet.

void xor(BitSet bitSet) - It performs XOR operation on the contents of the invoking BitSet object with those
specified by bitSet.

void clear( ) - It sets all the bits to zeros of the invoking BitSet.

void clear(int index) - It set the bit specified by given index to zero.

boolean equals(Object bitSet) - It retruns true if both invoking and argumented BitSets are equal, otherwise
returns false.

int length( ) - It returns the total number of bits in the invoking BitSet.

void set(int index) - It sets the bit specified by index.

String toString( ) - It returns the string equivalent of the invoking BitSet object.

DATE CLASS

The Date is a built-in class in java used to work with date and time in java. The Date class is available inside
the java.util package. The Date class represents the date and time with millisecond precision.

The Date class implements Serializable, Cloneable and Comparable interface.

The Date class in java has the following constructor.

Date( ) - It creates a Date object that represents current date and time.

Date(long milliseconds) - It creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.

Date(int year, int month, int date) - It creates a date object with the specified year, month, and date.

Date(int year, int month, int date, int hrs, int min) - It creates a date object with the specified year, month, date,
hours, and minuts.
Date(int year, int month, int date, int hrs, int min, int sec) - It creates a date object with the specified year, month,
date, hours, minuts and seconds.

Date(String s) - It creates a Date object and initializes it so that it represents the date and time indicated by the
string s, which is interpreted as if by the parse(java.lang.String) method.

The Date class in java has the following methods:

long getTime() - It returns the time represented by this date object.

boolean after(Date date) - It returns true, if the invoking date is after the argumented date.

boolean before(Date date) - It returns true, if the invoking date is before the argumented date.

Date from(Instant instant) - It returns an instance of Date object from Instant date.

void setTime(long time) - It changes the current date and time to given time.

int compareTo(Date date) - It compares current date with given date.

boolean equals(Date date) - It compares current date with given date for equality.

CALENDAR CLASS

The Calendar is a built-in abstract class in java used to convert date between a specific instant in time and a set of
calendar fields such as MONTH, YEAR, HOUR, etc. The Calendar class is available inside the java.util package.

As the Calendar class is an abstract class, we can not create an object using it.

We will use the static method Calendar.getInstance() to instantiate and implement a sub-class.

The Calendar class in java has the following methods.

Date getTime() - It returns a Date object representing the invoking Calendar's time value.

TimeZone getTimeZone() - It returns the time zone object associated with the invoking calendar.

String getCalendarType() - It returns an instance of Date object from Instant date.

int getFirstDayOfWeek() - It returns the day of the week in integer form.

void setTime(Date date) - It sets the Time of current calendar object.

void setTimeInMillis(long millis) - It sets the current time in millisecond.

void setTimeZone(TimeZone value) - It sets the TimeZone with passed TimeZone value.

RANDOM CLASS

The Random class is a part of java.util package.

The Random is a built-in class in java used to generate a stream of pseudo-random numbers in java programming.
The Random class provides several methods to generate random numbers of type integer, double, long, float etc.

The Random class is thread-safe.

Random number generation algorithm works on the seed value. If not provided, seed value is created from system
nano time.

The Random class in java has the following constructors.

Random() - It creates a new random number generator.

Random(long seedValue) - It creates a new random number generator using a single long seedValue.

FORMATTER CLASS

The Formatter is a built-in class in java used for layout justification and alignment, common formats for numeric,
string, and date/time data, and locale-specific output in java programming. The Formatter class is defined as final
class inside the java.util package.

The Formatter class in java has the following constructors.

Formatter() - It creates a new formatter.

Formatter(File file) - It creates a new formatter with the specified file.

Formatter(String fileName) - It creates a new formatter with the specified file name.

SCANNER CLASS:

The Scanner is a built-in class in java used for read the input from the user in java programming. The Scanner
class is defined inside the java.util package.

The Scanner class implements Iterator interface.

The Scanner class provides the easiest way to read input in a Java program.

The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter is whitespace.

The Scanner class in java has the following constructors.

Scanner(InputStream source) - It creates a new Scanner that produces values read from the specified input
stream.

Scanner(File source) - It creates a new Scanner that produces values scanned from the specified file.

Scanner(String source) - It creates a new Scanner that produces values scanned from the specified string.

Scanner(Readable source) - It creates a new Scanner that produces values scanned from the specified source.

You might also like