0% found this document useful (0 votes)
7 views

unit-4 java collections frame work

java collections framework topic wise notes

Uploaded by

P Revathy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

unit-4 java collections frame work

java collections framework topic wise notes

Uploaded by

P Revathy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 99

Collection Overview in java:

Java collection framework is a collection of interfaces and classes used to storing and
processing a group of individual objects as a single unit. The java collection framework holds
several classes that provide a large number of methods to store and process a group of objects.
These classes make the programmer task super easy and fast.

Java collection framework was introduced in java 1.2 version.

Java collection framework has the following hierarchy.


The java collection framework contains List, Queue, Set, and Map as top-level interfaces.

The List, Queue, and Set stores single value as its element, whereas Map stores a pair of a key
and value as its element.

The Collection interface


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

There is no direct implementation of this interface. However, it is implemented through its


subinterfaces like List, Set, and Queue.

For example, the ArrayList class implements the List interface which is a subinterface of
the Collection Interface.

Subinterfaces of Collection
The Collection interface includes subinterfaces that are implemented by various classes in Java.

1. List Interface

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

2. Set Interface

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

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

Methods of Collection
The Collection interface includes various methods that can be used to perform different
operations on objects. These methods are available in all its subinterfaces.

 add() - inserts the specified element to the collection

 size() - returns the size of the collection

 remove() - removes the specified element from the collection

 iterator() - returns an iterator to access elements of the collection

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

 removeAll() - removes all the elements of the specified collection from the collection

 clear() - removes all the elements of the collection

Java List interface


In Java, the List interface is an ordered collection that allows us to store and access elements
sequentially. It extends the Collection interface.

 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.
Classes that Implement List
Since List is an interface, we cannot create objects from it.

Classes implementing the List interface in Java

In order to use the functionalities of the List interface, we can use these classes:

 ArrayList
 LinkedList
 Vector
 Stack

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

In Java, we must import java.util.List package in order to use List.

SYNTAX:

// ArrayList implementation of List

List<String> list1 = new ArrayList<>();

// LinkedList implementation of List

List<String> list2 = new LinkedList<>();

Here, we have created objects list1 and list2 of classes ArrayList and LinkedList. These objects
can use the functionalities of the List interface.

Methods of List
The List interface includes all the methods of the Collection interface. Its because Collection is a
super interface of List.

Some of the commonly used methods of the Collection interface that's also available in the List
interface are:

Methods Description

add() adds an element to a list

addAll() adds all elements of one list to another

get() helps to randomly access elements from lists

iterator() returns iterator object that can be used to sequentially access elements of lists

set() changes elements of lists

remove() removes an element from the list

removeAll() removes all the elements from the list

clear() removes all the elements from the list (more efficient than removeAll())
size() returns the length of lists

toArray() converts a list into an array

contains() returns true if a list contains specific element

Example
import java.util.ArrayList;

import java.util.List;

public class ListInterfaceExample {

public static void main(String[] args) {

List list_1 = new ArrayList();

List<String> list_2 = new ArrayList<String>();

list_1.add(0, 10);

list_1.add(1, 20);

list_2.add(0, "BTech");

list_2.add(1, "Smart");

list_2.add(2, "Class");

list_1.addAll(1, list_2);

System.out.println("\nElements of list_1: " + list_1);

System.out.println("\nElement at index 3: " + list_1.get(3));

System.out.println("\nSublist : " + list_1.subList(2, 5));

list_1.set(2, 10);

System.out.println("\nAfter updating the value at index 2: " + list_1);

System.out.println("\nIndex of value 10: " + list_1.indexOf(10));

System.out.println("\nLast index of value 10: " + list_1.lastIndexOf(10));

}}
Java Queue Interface
The Queue interface is a child interface of the Collection interface. The Queue interface is
available inside the java.util package. It defines the methods that are commonly used by classes
like PriorityQueue and ArrayDeque.

The Queue is used to organize a sequence of elements prior to the actual operation.

 The Queue interface extends Collection interface.

 The Queue interface allows duplicate elements.

 The Queue interface preserves the order of insertion.

In order to use the functionalities of Queue, we need to use classes that implement it:

 ArrayDeque
 LinkedList
 PriorityQueue
ArrayDeque, LinkedList and PriorityQueue implements the Queue interface in Java.
Some of the commonly used methods of the Queue interface are:

The Queue interface defines the following methods.

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

add() - Inserts the specified element into the queue. If the task is successful, add() returns true,
if not it throws an exception.

offer() - Inserts the specified element into the queue. If the task is successful, offer() returns
true, if not it returns false.

element() - Returns the head of the queue. Throws an exception if the queue is empty.

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

remove() - Returns and removes the head of the queue. Throws an exception if the queue is
empty.

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

Example
import java.util.*;

public class QueueInterfaceExample {

public static void main(String[] args) {

Queue queue = new PriorityQueue();

queue.offer(10);

queue.offer(20);

queue.offer(30);

queue.offer(40);

System.out.println("\nQueue elements are - " + queue);

System.out.println("\nHead element - " + queue.element());

System.out.println("\nHead element again - " + queue.peek());

queue.remove();

System.out.println("\nElements after Head removal - " + queue);

queue.poll();

System.out.println("\nElements after one more Head removal - " + queue);

Java Deque Interface


The Deque interface is a child interface of the Queue interface. The Deque interface is available
inside the java.util package. It defines the methods that are used by class ArrayDeque.

 The Deque interface extends Queue interface.


 The Deque interface allows duplicate elements.
 The Deque interface preserves the order of insertion.

Methods of Deque
Since Deque extends the Queue interface, it inherits all the methods of the Queue interface.

Besides methods available in the Queue interface, the Deque interface also includes the
following methods:

addFirst() - Adds the specified element at the beginning of the deque. Throws an exception if
the deque is full.

addLast() - Adds the specified element at the end of the deque. Throws an exception if the
deque is full.

offerFirst() - Adds the specified element at the beginning of the deque. Returns false if the
deque is full.

offerLast() - Adds the specified element at the end of the deque. Returns false if the deque is
full.

getFirst() - Returns the first element of the deque. Throws an exception if the deque is empty.

getLast() - Returns the last element of the deque. Throws an exception if the deque is empty.

peekFirst() - Returns the first element of the deque. Returns null if the deque is empty.

peekLast() - Returns the last element of the deque. Returns null if the deque is empty.

removeFirst() - Returns and removes the first element of the deque. Throws an exception if the
deque is empty.

removeLast() - Returns and removes the last element of the deque. Throws an exception if the
deque is empty.

pollFirst() - Returns and removes the first element of the deque. Returns null if the deque is
empty.

pollLast() - Returns and removes the last element of the deque. Returns null if the deque is
empty.

Example
import java.util.*;

public class DequeInterfaceExample {


public static void main(String[] args) {

Deque deque = new ArrayDeque();

deque.addFirst(10);

deque.addLast(20);

deque.offerFirst(5);

deque.offerLast(25);

deque.push(2);

System.out.println("\nElements of deque - " + deque);

System.out.println("\nFirst element - " + deque.getFirst());

System.out.println("\nLast element - " + deque.getLast());

System.out.println("\nFirst element - " + deque.peekFirst());

System.out.println("\nLast element - " + deque.peekLast());

System.out.println("\nRemove first element - " + deque.pop());

System.out.println("\nRemove one more first element - " + deque.pollFirst());

System.out.println("\nRemove last element - " + deque.pollLast());

System.out.println("\nRemove one more first element - " +


deque.removeFirst());

System.out.println("\nRemove one more last element - " + deque.removeLast());

Java Set Interface


Set Interface
The Set interface is a child interface of Collection interface. It does not defines any additional
methods of it, it has all the methods that are inherited from Collection interface. The Set
interface does not allow duplicates. Set is a generic interface.

Classes that implement Set

Since Set is an interface, we cannot create objects from it.

In order to use functionalities of the Set interface, we can use these classes:

 HashSet
 LinkedHashSet
 EnumSet
 TreeSet

Interfaces that extend Set

The Set interface is also extended by these subinterfaces:

 SortedSet
 NavigableSet

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

// Set implementation using HashSet

Set<String> animals = new HashSet<>();

Here, we have created a Set called animals. We have used the HashSet class to implement the
Set interface.

Methods of Set

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

Some of the commonly used methods of the Collection interface that's also available in
the Set interface are:

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
The Java Set interface allows us to perform basic mathematical set operations like union,
intersection, and subset.

Union - to get the union of two sets x and y, we can use x.addAll(y)

Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)

Subset - to check if x is a subset of y, we can use y.containsAll(x)

Example:
import java.util.Set;

import java.util.HashSet;

class Main {

public static void main(String[] args) {

// Creating a set using the HashSet class

Set<Integer> set1 = new HashSet<>();

// Add elements to the set1


set1.add(2);

set1.add(3);

System.out.println("Set1: " + set1);

// Creating another set using the HashSet class

Set<Integer> set2 = new HashSet<>();

// Add elements

set2.add(1);

set2.add(2);

System.out.println("Set2: " + set2);

// Union of two sets

set2.addAll(set1);

System.out.println("Union is: " + set2);

Java SortedSet Interface


The SortedSet interface of the Java collections framework is used to store elements with some
order in a set.It extends the Set interface.

 The SortedSet interface extends Set interface.


 The SortedSet interface does not allow duplicate elements.
 The SortedSet interface organise the elements based on the ascending order.
Class that implements SortedSet
In order to use the functionalities of the SortedSet interface, we need to use the TreeSet class
that implements it.

To use SortedSet, we must import the java.util.SortedSet package first.

// SortedSet implementation by TreeSet class

SortedSet<String> animals = new TreeSet<>();

We have created a sorted set called animals using the TreeSet class.

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

comparator() - returns a comparator that can be used to order elements in the set

first() - returns the first element of the set

last() - returns the last element of the set

headSet(element) - returns all the elements of the set before the specified element

tailSet(element) - returns all the elements of the set after the specified element including the
specified element

subSet(element1, element2) - returns all the elements between the element1 and element2
including element1

Example
import java.util.*;

public class SortedSetInterfaceExample {

public static void main(String[] args) {

SortedSet sortedSet = new TreeSet();

sortedSet.add(10);

sortedSet.add(20);

sortedSet.add(5);

sortedSet.add(40);

sortedSet.add(30);

System.out.println("\nElements of sortedSet: " + sortedSet);

System.out.println("\nFirst element: " + sortedSet.first());

System.out.println("\nLast element: " + sortedSet.last());

System.out.println("\nSubset with upper limit: " + sortedSet.headSet(30));

System.out.println("\nSubset with lower limit: " + sortedSet.tailSet(30));

System.out.println("\nSubset with upper and lower limit: " +


sortedSet.subSet(10, 30));

Java NavigableSet Interface


The NavigableSet interface of the Java Collections framework provides the features to navigate
among the set elements.

It is considered as a type of SortedSet.

Class that implements NavigableSet


In order to use the functionalities of the NavigableSet interface, we need to use the TreeSet
class that implements NavigableSet.
The TreeSet class implements the NavigableSet interface.

In Java, we must import the java.util.NavigableSet package to use NavigableSet. Once we


import the package, here's how we can create navigable sets.

// SortedSet implementation by TreeSet class

NavigableSet<String> numbers = new TreeSet<>();

Here, we have created a navigable set named numbers of the TreeSet class.

Methods of NavigableSet
The NavigableSet is considered as a type of SortedSet. It is because NavigableSet extends the
SortedSet interface.Hence, all SortedSet methods are also available in NavigableSet.

However, some of the methods of SortedSet (headSet(), tailSet() and subSet()) are defined
differently in NavigableSet.

headSet(element, booleanValue)

The headSet() method returns all the elements of a navigable set before the specified element
(which is passed as an argument).

The booleanValue parameter is optional. Its default value is false.

If true is passed as a booleanValue, the method returns all the elements before the specified
element including the specified element.

tailSet(element, booleanValue)
The tailSet() method returns all the elements of a navigable set after the specified element
(which is passed as an argument) including the specified element.

The booleanValue parameter is optional. Its default value is true.

If false is passed as a booleanValue, the method returns all the elements after the specified
element without including the specified element.

subSet(e1, bv1, e2, bv2)

The subSet() method returns all the elements between e1 and e2 including e1.

The bv1 and bv2 are optional parameters. The default value of bv1 is true, and the default value
of bv2 is false.

If false is passed as bv1, the method returns all the elements between e1 and e2 without
including e1.

If true is passed as bv2, the method returns all the elements between e1 and e2, including e1.

Methods for Navigation


The NavigableSet provides various methods that can be used to navigate over its elements.

descendingSet() - reverses the order of elements in a set

descendingIterator() - returns an iterator that can be used to iterate over a set in reverse order

ceiling() - returns the lowest element among those elements that are greater than or equal to
the specified element

floor() - returns the greatest element among those elements that are less than or equal to the
specified element

higher() - returns the lowest element among those elements that are greater than the specified
element

lower() - returns the greatest element among those elements that are less than the specified
element

pollFirst() - returns and removes the first element from the set

pollLast() - returns and removes the last element from the set

Example
import java.util.*;

public class NavigableSetInterfaceExample {

public static void main(String[] args) {

NavigableSet navSet = new TreeSet();

navSet.add(10);

navSet.add(20);

navSet.add(5);

navSet.add(40);

navSet.add(30);

System.out.println("\nElements of sortedSet: " + navSet);

System.out.println("\nSmallest element from subSet of larger than 25: " + navSet.ceiling(25));

System.out.println("\nLargest element from subSet of smaller than 25: " + navSet.floor(25));

System.out.println("\nSmallest element from subSet of larger than 25: " + navSet.higher(25));

System.out.println("\nLargest element from subSet of smaller than 25: " + navSet.lower(25));

System.out.println("\nSubset with upperBound, including it: " + navSet.headSet(30, true));

System.out.println("\nSubset with upperBound, excluding it: " + navSet.headSet(30, false));

System.out.println("\nSubset with lowwerBound, including it: " + navSet.tailSet(30, true));

System.out.println("\nSubset with lowerBound, excluding it: " + navSet.tailSet(30, false));

System.out.println("\nRemove the first element: " + navSet.pollFirst());

System.out.println("\nRemove the lastelement: " + navSet.pollLast());

}
Collection classes in java:

ArrayList class:
In Java, we use the ArrayList class to implement the functionality of resizable-arrays.

It implements the List interface of the collections framework .

Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first. Here is how we
can create arraylists in Java:

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

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

// create Integer type arraylist

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

Basic Operations on ArrayList


The ArrayList class provides various methods to perform different operations on arraylists.
Some commonly used arraylist operations are

 Add elements
 Access elements
 Change elements
 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.

For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
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 languages.

2. Access ArrayList Elements


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

For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
animals.add("Cat");
animals.add("Dog");
animals.add("Cow");
System.out.println("ArrayList: " + animals);

String str = animals.get(1);


System.out.print("Element at index 1: " + str);
}
}
Output
ArrayList: [Cat, Dog, Cow]
Element at index 1: Dog

In the above example, we have used the get() method with parameter 1. Here, the
method returns the element at index 1.
We can also access elements of the ArrayList using the iterator() method.

3. Change ArrayList Elements


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

For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Kotlin");
languages.add("C++");
System.out.println("ArrayList: " + languages);
languages.set(2, "JavaScript");
System.out.println("Modified ArrayList: " + languages);
}
}
Output
ArrayList: [Java, Kotlin, C++]
Modified ArrayList: [Java, Kotlin, JavaScript]

In the above example, we have created an ArrayList named languages. Notice the
line,language.set(2, "JavaScript");
Here, the set() method changes the element at index 2 to JavaScript.
4. Remove ArrayList Elements
To remove an element from the arraylist, we can use the remove() method of the ArrayList
class. For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
System.out.println("ArrayList: " + animals);
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

Here, the remove() method takes the index number as the parameter. And, removes the
element specified by the index number.

Methods of ArrayList Class

Besides the above basic methods, there are some more ArrayList methods that are
commonly used.

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

Java LinkedList class


The LinkedList class of the Java collections framework provides the functionality of the linked list
data structure (doubly linkedlist).

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. For example,

// create Integer type linked list

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

Basic operations of Java LinkedList


LinkedList provides various methods that allow us to perform different operations in linked lists. The
four commonly used LinkedList Operations are

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

1. Add elements to a LinkedList

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

import java.util.LinkedList;

class Main {

public static void main(String[] args){

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

animals.add("Dog");

animals.add("Cat");

animals.add("Cow");

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

animals.add(1, "Horse");

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

Output

LinkedList: [Dog, Cat, Cow]

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

In the above example, we have created a LinkedList named animals. Here, we have used the add()
method to add elements to animals.

2. Access LinkedList elements

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

import java.util.LinkedList;

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

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

languages.add("Python");

languages.add("Java");

languages.add("JavaScript");

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

String str = languages.get(1);

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

Output

LinkedList: [Python, Java, JavaScript]

Element at index 1: Java

In the above example, we have used the get() method with parameter 1. Here, the method returns the
element at index 1.

3. Change Elements of a LinkedList

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

import java.util.LinkedList;

class Main {

public static void main(String[] args) {

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

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

languages.add("Java");

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


languages.set(3, "Kotlin");

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

Output

LinkedList: [Java, Python, JavaScript, Java]

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

In the above example, we have created a LinkedList named languages. Notice the line,

languages.set(3, "Kotlin");

Here, the set() method changes the element at index 3 to Kotlin.

4. Remove element from a LinkedList

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

import java.util.LinkedList;

class Main {

public static void main(String[] args) {

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

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

languages.add("Kotlin");

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

String str = languages.remove(1);

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

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

}
}

Output

LinkedList: [Java, Python, JavaScript, Kotlin]

Removed Element: Python

New LinkedList: [Java, JavaScript, Kotlin]

Here, the remove() method takes the index number as the parameter. And, removes the element
specified by the index number.

Other Methods
Methods Description

contains() checks if the LinkedList contains the element

indexOf() returns the index of the first occurrence of the element

lastIndexOf() returns the index of the last occurrence of the element

clear() removes all the elements of the LinkedList

iterator() returns an iterator to iterate over LinkedList

Java HashSet Class


The HashSet class of the Java Collections framework provides the functionalities of the hash table data
structure.

It implements the Set interface.


Creating a HashSet

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

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

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

For example,

import java.util.HashSet;

class Main {

public static void main(String[] args) {

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

evenNumber.add(2);

evenNumber.add(4);

evenNumber.add(6);

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

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

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. For example,

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);

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

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

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

For example,

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);

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

Set operations
The various methods of the HashSet class can also be used to perform various set operations.

Union of Sets
To perform the union between two sets, we can use the addAll() method. For example,

import java.util.HashSet;

class Main {

public static void main(String[] args) {

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

evenNumbers.add(2);

evenNumbers.add(4);

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

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

numbers.add(1);

numbers.add(3);

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

// Union of two set

numbers.addAll(evenNumbers);

System.out.println("Union is: " + numbers);

Output

HashSet1: [2, 4]

HashSet2: [1, 3]
Union is: [1, 2, 3, 4]

Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method. For example

import java.util.HashSet;

class Main {

public static void main(String[] args) {

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

primeNumbers.add(2);

primeNumbers.add(3);

System.out.println("HashSet1: " + primeNumbers);

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

evenNumbers.add(2);

evenNumbers.add(4);

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

// Intersection of two sets

evenNumbers.retainAll(primeNumbers);

System.out.println("Intersection is: " + evenNumbers);

Output

HashSet1: [2, 3]

HashSet2: [2, 4]

Intersection is: [2]

Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method. For example,

import java.util.HashSet;

class Main {

public static void main(String[] args) {

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

primeNumbers.add(2);

primeNumbers.add(3);

primeNumbers.add(5);

System.out.println("HashSet1: " + primeNumbers);

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

oddNumbers.add(1);

oddNumbers.add(3);

oddNumbers.add(5);

System.out.println("HashSet2: " + oddNumbers);

// Difference between HashSet1 and HashSet2

primeNumbers.removeAll(oddNumbers);

System.out.println("Difference : " + primeNumbers);

Output

HashSet1: [2, 3, 5]

HashSet2: [1, 3, 5]

Difference: [2]

Subset
To check if a set is a subset of another set or not, we can use the containsAll() method. For example,
import java.util.HashSet;

class Main {

public static void main(String[] args) {

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

numbers.add(1);

numbers.add(2);

numbers.add(3);

numbers.add(4);

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

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

primeNumbers.add(2);

primeNumbers.add(3);

System.out.println("HashSet2: " + primeNumbers);

// Check if primeNumbers is a subset of numbers

boolean result = numbers.containsAll(primeNumbers);

System.out.println("Is HashSet2 is subset of HashSet1? " + result);

Output

HashSet1: [1, 2, 3, 4]

HashSet2: [2, 3]

Is HashSet2 is a subset of HashSet1? true

Other Methods Of HashSet


Method Description

clone() Creates a copy of the HashSet


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

isEmpty() Checks if the HashSet is empty

size() Returns the size of the HashSet

clear() Removes all the elements from the HashSet

Java TreeSet
The TreeSet class of the Java collections framework provides the functionality of a tree data structure.

It extends the NavigableSet interface.

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

Once we import the package, here is how we can create a TreeSet in Java

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

Methods of TreeSet
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

For example,

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


For example,

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

Methods for Navigation


Since the TreeSet class implements NavigableSet, it provides various methods to navigate over the
elements of the tree set.

1. first() and last() Methods


first() - returns the first element of the set

last() - returns the last element of the set

For example,

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 first() method

int first = numbers.first();

System.out.println("First Number: " + first);

// Using the last() method

int last = numbers.last();

System.out.println("Last Number: " + last);

Output

TreeSet: [2, 5, 6]

First Number: 2

Last Number: 6

2. ceiling(), floor(), higher() and lower() Methods


higher(element) - Returns the lowest element among those elements that are greater than the specified
element.

lower(element) - Returns the greatest element among those elements that are less than the specified
element.

ceiling(element) - Returns the lowest element among those elements that are greater than the specified
element. If the element passed exists in a tree set, it returns the element passed as an argument.

floor(element) - Returns the greatest element among those elements that are less than the specified
element. If the element passed exists in a tree set, it returns the element passed as an argument.

For example,

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(4);

numbers.add(6);

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

// Using higher()

System.out.println("Using higher: " + numbers.higher(4));

// Using lower()

System.out.println("Using lower: " + numbers.lower(4));

// Using ceiling()

System.out.println("Using ceiling: " + numbers.ceiling(4));

// Using floor()

System.out.println("Using floor: " + numbers.floor(3));

}
}

Output

TreeSet: [2, 4, 5, 6]

Using higher: 5

Using lower: 2

Using ceiling: 4

Using floor: 2

3. pollfirst() and pollLast() Methods


pollFirst() - returns and removes the first element from the set

pollLast() - returns and removes the last element from the set

For example,

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(4);

numbers.add(6);

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

// Using pollFirst()

System.out.println("Removed First Element: " + numbers.pollFirst());

// Using pollLast()

System.out.println("Removed Last Element: " + numbers.pollLast());


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

Output

TreeSet: [2, 4, 5, 6]

Removed First Element: 2

Removed Last Element: 6

New TreeSet: [4, 5]

4. headSet(), tailSet() and subSet() Methods


headSet(element, booleanValue)

The headSet() method returns all the elements of a tree set before the specified element (which is
passed as an argument).

The booleanValue parameter is optional. Its default value is false.

If true is passed as a booleanValue, the method returns all the elements before the specified element
including the specified element.

For example,

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(4);

numbers.add(6);

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

// Using headSet() with default boolean value


System.out.println("Using headSet without boolean value: " + numbers.headSet(5));

// Using headSet() with specified boolean value

System.out.println("Using headSet with boolean value: " + numbers.headSet(5, true));

Output

TreeSet: [2, 4, 5, 6]

Using headSet without boolean value: [2, 4]

Using headSet with boolean value: [2, 4, 5]

tailSet(element, booleanValue)
The tailSet() method returns all the elements of a tree set after the specified element (which is passed as
a parameter) including the specified element.

The booleanValue parameter is optional. Its default value is true.

If false is passed as a booleanValue, the method returns all the elements after the specified element
without including the specified element.

For example,

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(4);

numbers.add(6);

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

// Using tailSet() with default boolean value


System.out.println("Using tailSet without boolean value: " + numbers.tailSet(4));

// Using tailSet() with specified boolean value

System.out.println("Using tailSet with boolean value: " + numbers.tailSet(4, false));

Output
TreeSet: [2, 4, 5, 6]

Using tailSet without boolean value: [4, 5, 6]

Using tailSet with boolean value: [5, 6]

subSet(e1, bv1, e2, bv2)


The subSet() method returns all the elements between e1 and e2 including e1.

The bv1 and bv2 are optional parameters. The default value of bv1 is true, and the default value of bv2
is false.

If false is passed as bv1, the method returns all the elements between e1 and e2 without including e1.

If true is passed as bv2, the method returns all the elements between e1 and e2, including e1.

For example,

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(4);

numbers.add(6);

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


// Using subSet() with default boolean value

System.out.println("Using subSet without boolean value: " + numbers.subSet(4, 6));

// Using subSet() with specified boolean value

System.out.println("Using subSet with boolean value: " + numbers.subSet(4, false, 6, true));

Output

TreeSet: [2, 4, 5, 6]

Using subSet without boolean value: [4, 5]

Using subSet with boolean value: [5, 6]

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

It implements the Queue interface.

Unlike normal queues, priority queue elements are retrieved in sorted order.

Suppose, we want to retrieve elements in the ascending order. In this case, the head of the priority
queue will be the smallest element. Once this element is retrieved, the next smallest element will be the
head of the queue.

Creating PriorityQueue
In order to create a priority queue, we must import the java.util.PriorityQueue package. Once we import
the package, here is how we can create a priority queue in Java.

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

Methods of PriorityQueue
The PriorityQueue class provides the implementation of all the methods present in the Queue interface.

Insert Elements to PriorityQueue


add() - Inserts the specified element to the queue. If the queue is full, it throws an exception.

offer() - Inserts the specified element to the queue. If the queue is full, it returns false.

For example,

import java.util.PriorityQueue;

class Main {

public static void main(String[] args) {

// Creating a priority queue

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

// Using the add() method

numbers.add(4);

numbers.add(2);

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

// Using the offer() method

numbers.offer(1);

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

Output
PriorityQueue: [2, 4]

Updated PriorityQueue: [1, 4, 2]

Here, we have created a priority queue named numbers. We have inserted 4 and 2 to the queue.

Access PriorityQueue Elements


To access elements from a priority queue, we can use the peek() method. This method returns the head
of the queue. For example,

import java.util.PriorityQueue;

class Main {

public static void main(String[] args) {

// Creating a priority queue

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

numbers.add(4);

numbers.add(2);

numbers.add(1);

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

// Using the peek() method

int number = numbers.peek();

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

Output

PriorityQueue: [1, 4, 2]

Accessed Element: 1

Remove PriorityQueue Elements


remove() - removes the specified element from the queue

poll() - returns and removes the head of the queue

For example,

import java.util.PriorityQueue;

class Main {

public static void main(String[] args) {

// Creating a priority queue

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

numbers.add(4);

numbers.add(2);

numbers.add(1);

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

// Using the remove() method

boolean result = numbers.remove(2);

System.out.println("Is the element 2 removed? " + result);

// Using the poll() method

int number = numbers.poll();

System.out.println("Removed Element Using poll(): " + number);

Output

PriorityQueue: [1, 4, 2]

Is the element 2 removed? true

Removed Element Using poll(): 1


Iterating Over a PriorityQueue
To iterate over the elements of a priority queue, we can use the iterator() method. In order to use this
method, we must import the java.util.Iterator package. For example,

import java.util.PriorityQueue;

import java.util.Iterator;

class Main {

public static void main(String[] args) {

// Creating a priority queue

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

numbers.add(4);

numbers.add(2);

numbers.add(1);

System.out.print("PriorityQueue using iterator(): ");

//Using the iterator() method

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

while(iterate.hasNext()) {

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

System.out.print(", ");

Output

PriorityQueue using iterator(): 1, 4, 2,

Other PriorityQueue Methods

Methods Descriptions
contains(element) Searches the priority queue for the specified element.

If the element is found, it returns true, if not it returns false.

size() Returns the length of the priority queue.

toArray() Converts a priority queue to an array and returns it.

Java ArrayDeque class


In Java, we can use the ArrayDeque class to implement queue and deque data structures using arrays.

Interfaces implemented by ArrayDeque

The ArrayDeque class implements these two interfaces:

 Java Queue Interface


 Java Deque Interface

Creating ArrayDeque

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

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

Here, Type indicates the type of the array deque. For example,

// Creating String type ArrayDeque

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

Methods of ArrayDeque

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

Insert Elements to Deque

1. Add elements using add(), addFirst() and addLast()

add() - inserts the specified element at the end of the array deque

addFirst() - inserts the specified element at the beginning of the array deque

addLast() - inserts the specified at the end of the array deque (equivalent to add())
Note: If the array deque is full, all these methods add(), addFirst() and addLast() throws
IllegalStateException.

For example,

import java.util.ArrayDeque;

class Main {

public static void main(String[] args) {

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

// Using add()

animals.add("Dog");

// Using addFirst()

animals.addFirst("Cat");

// Using addLast()

animals.addLast("Horse");

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

Output

ArrayDeque: [Cat, Dog, Horse]

2. Insert elements using offer(), offerFirst() and offerLast()


offer() - inserts the specified element at the end of the array deque

offerFirst() - inserts the specified element at the beginning of the array deque

offerLast() - inserts the specified element at the end of the array deque

Note: offer(), offerFirst() and offerLast() returns true if the element is successfully inserted; if the array
deque is full, these methods return false.

For example,
import java.util.ArrayDeque;

class Main {

public static void main(String[] args) {

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

// Using offer()

animals.offer("Dog");

// Using offerFirst()

animals.offerFirst("Cat");

// Using offerLast()

animals.offerLast("Horse");

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

Output

ArrayDeque: [Cat, Dog, Horse]

Note: If the array deque is full

the add() method will throw an exception

the offer() method returns false

Access ArrayDeque Elements


1. Access elements using getFirst() and getLast()

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

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

Note: If the array deque is empty, getFirst() and getLast() throws NoSuchElementException.

For example,

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);

// Get the first element

String firstElement = animals.getFirst();

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

// Get the last element

String lastElement = animals.getLast();

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

Output

ArrayDeque: [Dog, Cat, Horse]

First Element: Dog

Last Element: Horse

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

For example,

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

Note: If the array deque is empty, peek(), peekFirst() and getLast() throws NoSuchElementException.

Remove ArrayDeque Elements


1. Remove elements using the remove(), removeFirst(), removeLast() method

remove() - returns and removes an element from the first element of the array deque

remove(element) - returns and removes the specified element from the head of the array deque

removeFirst() - returns and removes the first element from the array deque (equivalent to remove())

removeLast() - returns and removes the last element from the array deque

Note: If the array deque is empty, remove(), removeFirst() and removeLast() method throws an
exception. Also, remove(element) throws an exception if the element is not found.

For example,

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("Cow");

animals.add("Horse");

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

// Using remove()

String element = animals.remove();

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

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

// Using removeFirst()

String firstElement = animals.removeFirst();

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

// Using removeLast()

String lastElement = animals.removeLast();


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

Output

ArrayDeque: [Dog, Cat, Cow, Horse]

Removed Element: Dog

New ArrayDeque: [Cat, Cow, Horse]

Removed First Element: Cat

Removed Last Element: Horse

2. Remove elements using the poll(), pollFirst() and pollLast() method

poll() - returns and removes the first element of the array deque

pollFirst() - returns and removes the first element of the array deque (equivalent to poll())

pollLast() - returns and removes the last element of the array deque

Note: If the array deque is empty, poll(), pollFirst() and pollLast() returns null if the element is not found.

For example,

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("Cow");

animals.add("Horse");

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


// Using poll()

String element = animals.poll();

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

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

// Using pollFirst()

String firstElement = animals.pollFirst();

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

// Using pollLast()

String lastElement = animals.pollLast();

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

Output

ArrayDeque: [Dog, Cat, Cow, Horse]

Removed Element: Dog

New ArrayDeque: [Cat, Cow, Horse]

Removed First Element: Cat

Removed Last Element: Horse

3. Remove Element: using the clear() method

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

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);

Output

ArrayDeque: [Dog, Cat, Horse]

New ArrayDeque: []

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. For example,

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]

Other Methods

Methods Descriptions

element() Returns an element from the head of the array deque.

contains(element) Searches the array deque for the specified element.

If the element is found, it returns true, if not it returns false.

size() Returns the length of the array deque.


toArray() Converts array deque to array and returns it.

clone() Creates a copy of the array deque and returns it.

Accessing a Java Collection via a Iterator


The java collection framework often we want to cycle through the elements. For example, we might
want to display each element of a collection. The java provides an interface Iterator that is available
inside the java.util package to cycle through each element of a collection.

 The Iterator allows us to move only forward direction.


 The Iterator does not support the replacement and addition of new elements.

We use the following steps to access a collection of elements using the Iterator.

Step - 1: Create an object of the Iterator by calling collection.itertor( ) method.

Step - 2: Use the method hasNext( ) to access to check does the collection has the next element. (Use a
loop).

Step - 3: Use the method next( ) to access each element from the collection. (use inside the loop).

The Iterator has the following methods.

Method Description

iterator( ) Used to obtain an iterator to the start of the collection.

hasNext( ) Returns true if the collection has the next element, otherwise, it returns false.

next( ) Returns the next element available in the collection.

Example
import java.io.*;

import java.util.*;

public class JavaIteratorExample {

public static void main(String[] args)


{

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

cityNames.add("Delhi");

cityNames.add("Mumbai");

cityNames.add("Kolkata");

cityNames.add("Chandigarh");

cityNames.add("Noida");

// Iterator to iterate the cityNames

Iterator iterator = cityNames.iterator();

System.out.println("CityNames elements : ");

while (iterator.hasNext())

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

System.out.println();

Output:

CityNames elements:

Delhi Mumbai Kolkata Chandigarh Noida

for-each alternative
The Java for-each loop an alternative approach to traverse the array or collection in Java. It is mainly
used to traverse the array or collection elements. The advantage of the for-each loop is that it eliminates
the possibility of bugs and makes the code more readable. It is known as the for-each loop because it
traverses each element one by one.

The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order

Syntax :

for(data_type variable : array /collection){


//body of for-each loop

Example

import java.util.*;

class ForEachExample2{

public static void main(String args[]){

//Creating a list of elements

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

list.add("vimal");

list.add("sonoo");

list.add("ratan");

//traversing the list of elements using for-each loop

for(String s:list){

System.out.println(s); } } }

Output:

vimal

sonoo

rattan
Map interfaces and classes:

The java collection framework has an interface Map that is available inside the
java.util package. The Map interface is not a subtype of Collection interface.

 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.
 In a Map, the order of elements depends on specific implementations, e.g
TreeMap and LinkedHashMap have predictable order, while HashMap does
not.

The Map interface has the following child interfaces.

Interface Description

Map Maps unique key to value.

Map.Entry Describe an element in key and value pair in a map.

Entry is sub interface of Map.

SortedMap It is a child of Map so that key are maintained in an ascending order.

NavigableMap It is a child of SortedMap to handle the retrieval of entries based


on closest match searches.

The Map interface has the following three classes.

Class Description
HashMap It implements the Map interface, but it doesn't maintain any
order.

LinkedHashMap It implements the Map interface, it also extends HashMap


class. It maintains the insertion order.

TreeMap It implements the Map and SortedMap interfaces. It maintains the


ascending order.

In Java, we must import the java.util.Map package in order to use Map. Once we
import the package, we can create a map as

// Map implementation using HashMap

Map<Key, Value> numbers = new HashMap<>();

Here,

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

Value - elements associated by keys in a map

Methods of Map

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

Besides methods available in the Collection interface, the Map interface also
includes the following methods:

1. 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.
2. putAll() - Inserts all the entries from the specified map to this map.
3. putIfAbsent(K, V) - Inserts the association if the key K is not already
associated with the value V.
4. get(K) - Returns the value associated with the specified key K. If the key is
not found, it returns null.
5. getOrDefault(K, defaultValue) - Returns the value associated with the
specified key K. If the key is not found, it returns the defaultValue.
6. containsKey(K) - Checks if the specified key K is present in the map or not.
7. containsValue(V) - Checks if the specified value V is present in the map or
not.
8. replace(K, V) - Replace the value of the key K with the new specified value
V.
9. 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.
10.remove(K) - Removes the entry from the map represented by the key K.
11.remove(K, V) - Removes the entry from the map that has key K associated
with value V.
12.keySet() - Returns a set of all the keys present in a map.
13.values() - Returns a set of all the values present in a map.
14.entrySet() - Returns a set of all the key/value mapping present in a map.

Map classes in java:-

Java HashMap class

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.

The HashMap class implements the Map interface.


Create a HashMap

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


package first. Once we import the package, we can create hashmaps in Java as

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.

Basic Operations on Java HashMap

The HashMap class provides various methods to perform different operations on


hashmaps. some commonly used arraylist operations are

 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. For example,

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}

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


have used the put() method to add elements to numbers.

Notice the statement,

2. Access HashMap Elements

We can access the keys, values, and key/value pairs of the hashmap as set views
using keySet(), values(), and entrySet() methods respectively. For example,

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);

// return set view of keys

// using keySet()

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

// return set view of values

// using values()

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

// return set view of key/value pairs

// using entrySet()

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

Output

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

Keys: [1, 2, 3]

Values: [Java, Python, JavaScript]

Key/Value mappings: [1=Java, 2=Python, 3=JavaScript]

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


are accessing the keys, values, and key/value mappings from the hashmap.
3. Change HashMap Value

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

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}

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

4. Remove HashMap Elements


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

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}


Here, the remove() method takes the key as its parameter. It then returns the
value associated with the key and removes the entry.

Other Methods of HashMap

Method Description

clear() removes all mappings from the HashMap

compute() computes a new value for the specified key

computeIfAbsent()computes value if a mapping for the key is not present

computeIfPresent() computes a value for mapping if the key is present

merge() merges the specified mapping to the HashMap

clone() makes the copy of the HashMap

containsKey() checks if the specified key is present in Hashmap

containsValue() checks if Hashmap contains the specified value

size() returns the number of items in HashMap

isEmpty() checks if the Hashmap is empty

LinkedHashMap Class

The LinkedHashMap class is a child class of HashMap, and it implements the Map
interface. The LinkedHashMap is used to store the data in the form of key, value
pair using hash table and linked list concepts.

Key Properties of LinkedHashMap

 LinkedHashMap is a child class of HashMap class.


 LinkedHashMap implements the Map interface.
 LinkedHashMap stores data as a pair of key and value.
 LinkedHashMap uses Hash table concept to store the data.
 LinkedHashMap does not allow duplicate keys, but values may be repeated.
 LinkedHashMap allows only one null key and multiple null values.
 LinkedHashMap follows the insertion order.
 LinkedHashMap has the default capacity 16 entries.

Example

import java.util.*;

public class HashMapExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

LinkedHashMap employeeInfo = new LinkedHashMap();

LinkedHashMap contactInfo = new LinkedHashMap();

employeeInfo.put(1, "Raja");

employeeInfo.put(2, "Gouthami");

employeeInfo.put(3, "Heyansh");

employeeInfo.put(4, "Yamini");

employeeInfo.put(5, "ManuTej");

System.out.println("Employee Information\n" + employeeInfo);

System.out.println("\nPlease enter the ID and Contact number");

System.out.println("Employee IDs : " + employeeInfo.keySet());

System.out.print("Enter ID: ");

int id = read.nextInt();

System.out.print("Enter Contact Number: ");


long contactNo = read.nextLong();

if(employeeInfo.containsKey(id)) {

contactInfo.put(id, contactNo);

System.out.println("\n\nEmployee Contact Information\n");

System.out.println("ID - " + id);

System.out.println("Name - " + employeeInfo.get(id));

System.out.println("Contact Number - " + contactInfo.get(id));

TreeMap Class

The TreeMap class is a child class of AbstractMap, and it implements the


NavigableMap interface which is a child interface of SortedMap. The TreeMap is
used to store the data in the form of key, value pair using a red-black tree
concepts.

Key Properties of TreeMap

 TreeMap is a child class of AbstractMap class.


 TreeMap implements the NavigableMap interface which is a child interface
of SortedMap interface.
 TreeMap stores data as a pair of key and value.
 TreeMap uses red-black tree concept to store the data.
 TreeMap does not allow duplicate keys, but values may be repeated.
 TreeMap does not allow null key, but allows null values.
 TreeMap follows the ascending oreder based on keys.
Example

import java.util.*;

public class HashMapExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

TreeMap employeeInfo = new TreeMap();

TreeMap contactInfo = new TreeMap();

employeeInfo.put(1, "Raja");

employeeInfo.put(4, "Gouthami");

employeeInfo.put(5, "Heyansh");

employeeInfo.put(3, "Yamini");

employeeInfo.put(2, "ManuTej");

System.out.println("Employee Information\n" + employeeInfo);

System.out.println("\nPlease enter the ID and Contact number");

System.out.println("Employee IDs : " + employeeInfo.keySet());

System.out.print("Enter ID: ");

int id = read.nextInt();

System.out.print("Enter Contact Number: ");

long contactNo = read.nextLong();

if(employeeInfo.containsKey(id)) {

contactInfo.put(id, contactNo);
}

System.out.println("\n\nEmployee Contact Information\n");

System.out.println("ID - " + id);

System.out.println("Name - " + employeeInfo.get(id));

System.out.println("Contact Number - " + contactInfo.get(id));

}}

WeakHashMap class

The WeakHashMap class of the Java collections framework provides the feature
of the hash table data structure.

It implements the Map interface.

Create a WeakHashMap

In order to create a weak hashmap, we must import the java.util.WeakHashMap


package first. Once we import the package, we can create weak hashmaps in Java.

WeakHashMap<Key, Value> numbers = new WeakHashMap<>;

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

Value - elements associated by keys in a map

Example:

import java.util.WeakHashMap;

class Main {

public static void main(String[] args) {

// Creating WeakHashMap of numbers

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


String two = new String("Two");

Integer twoValue = 2;

String four = new String("Four");

Integer fourValue = 4;

// Inserting elements

numbers.put(two, twoValue);

numbers.put(four, fourValue);

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

// Make the reference null

two = null;

// Perform garbage collection

System.gc();

System.out.println("WeakHashMap after garbage collection: " + numbers);

Output

WeakHashMap: {Four=4, Two=2}

WeakHashMap after garbage collection: {Four}

As we can see, when the key two of a weak hashmap is set to null and perform
garbage collection, the key is removed.

It is because unlike hashmaps, keys of weak hashmaps are of weak reference


type. This means the entry of a map are removed by the garbage collector if the
key to that entry is no longer used. This is useful to save resources.
Comparators in java

The Comparator is an interface available in the java.util package. The java


Comparator is used to order the objects of user-defined classes. The java
Comparator can compare two objects from two different classes.

Using the java Comparator, we can sort the elements based on data members of a
class. For example, we can sort based on rollNo, age, salary, marks, etc.

The Comparator interface has the following methods.

Method Description

int compare(Object obj1, Object obj2) It is used to compares the obj1 with o bj2 .

boolean equals(Object obj) It is used to check the equity between


current object and argumented object.

The Comparator can be used in the following three ways.

 Using a separate class that implements Comparator interface.


 Using anonymous class.
 Using lamda expression.
Example

import java.util.*;

class Student{

String name;
float percentage;

Student(String name, float percentage){


this.name = name;
this.percentage = percentage;
}

}
class PercentageComparator implements Comparator<Student>{
public int compare(Student stud1, Student stud2) {
if(stud1.percentage < stud2.percentage)
return 1;
return -1;
}
}

public class StudentCompare{

public static void main(String args[]) {

ArrayList<Student> studList = new ArrayList<Student>();

studList.add(new Student("Gouthami", 90.61f));


studList.add(new Student("Raja", 83.55f));
studList.add(new Student("Honey", 85.55f));
studList.add(new Student("Teja", 77.56f));
studList.add(new Student("Varshith", 80.89f));

Comparator<Student> com = new PercentageComparator();

Collections.sort(studList, com);

System.out.println("Avg % --> Name");


System.out.println("---------------------");
for(Student stud:studList) {
System.out.println(stud.percentage + " --> " + stud.name);
}
}
}

Collection algorithms in java

The java collection framework defines several algorithms as static methods that can be used
with collections and map objects.
All the collection algorithms in the java are defined in a class called Collections which defined in
the java.util package.
Method Description
max(Collection c) Returns the largest element from the collection c as
determined by natural ordering.
min(Collection c) Returns the smallest element from the collection c as
determined by natural ordering.
void reverse(List Reverses all the elements sequence in list.
list)
void shuffle(List Shuffles the elements in list.
list)
void sort(List list) Sorts the elements of the list as determined by their natural
ordering.

Example
import java.util.*;

public class CollectionAlgorithmsExample {

public static void main(String[] args) {

ArrayList list = new ArrayList();


PriorityQueue queue = new PriorityQueue();
HashSet set = new HashSet();
HashMap map = new HashMap();

Random num = new Random();

for(int i = 0; i < 5; i++) {


list.add(num.nextInt(100));
queue.add(num.nextInt(100));
set.add(num.nextInt(100));
map.put(i, num.nextInt(100));
}

System.out.println("List => " + list);


System.out.println("Queue => " + queue);
System.out.println("Set => " + set);
System.out.println("Map => " + map);
System.out.println("---------------------------------------");

Collections.sort(list);
System.out.println("List in ascending order => " + list);

System.out.println("Largest element in set => " + Collections.max(set));

System.out.println("Smallest element in queue => " + Collections.min(queue));


Collections.reverse(list);
System.out.println("List in reverse order => " + list);

Collections.shuffle(list);
System.out.println("List after shuffle => " + list);
}
}

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.
List<T> asList(T[] arr) It returns a fixed-size list backed by the specified
Arrays.
int binarySearch(T[] arr, It searches for the specified element in the array with
element) the help of Binary Search algorithm, and returns the
position.
boolean equals(T[] It returns true if the two specified arrays of booleans
arr1, T[] arr2) are equal to one another, otherwise retruns false.
int hashCode(T[] arr) It returns the hash code for the specified array.
void fill(T[] arr, T value) It assigns the specified value to each element of the
specified array.
void sort(T[] arr) It sorts the specified array into ascending order.

Example
import java.util.*;

public class ArraysClassExample {

public static void main(String[] args) {

int[] arr1 = {10, 3, 50, 7, 30, 66, 28, 54, 42};


int[] arr2 = {67, 2, 54, 67, 13, 56, 98};

System.out.print("Array1 => ");


for(int i:arr1)
System.out.print(i + ", ");
System.out.print("\nArray2 => ");
for(int i:arr2)
System.out.print(i + ", ");
System.out.println("\n-------------------------------------------");

System.out.println("Array1 as List => " + Arrays.asList(arr1));

System.out.println("Position of 30 in Array1 => " + Arrays.binarySearch(arr1, 30));

System.out.println("equity of array1 and array2 => " + Arrays.equals(arr1, arr2));

System.out.println("Hash code of Array1 => " + Arrays.hashCode(arr1));

Arrays.fill(arr1, 15);
System.out.print("fill Array1 with 15 => ");
for(int i:arr1)
System.out.print(i + ", ");

Arrays.sort(arr2);
System.out.print("\nArray2 in sorted order => ");
for(int i:arr2)
System.out.print(i + ", ");
}
}

Legacy classes and interfaces:

Dictionary class
 In java, the package java.util contains a class called Dictionary which works like a Map.
The Dictionary is an abstract class used to store and manage elements in the form of a
pair of key and value.
 The Dictionary stores data as a pair of key and value. In the dictionary, each key
associates with a value. We can use the key to retrieve the value back when needed.
 As Dictionary is an abstract class we can not create its object. It needs a child class like
Hashtable.
The Dictionary class in java has the following methods.
S.
No. Methods with Description
1 Dictionary( )
It's a constructor.
2 Object put(Object key, Object value)
Inserts a key and its value into the dictionary. Returns null on success;
returns the previous value associated with the key if the key is already
exist.
3 Object remove(Object key)
It returns the value associated with given key and removes the same;
Returns null if the key does not exist.
4 Object get(Object key)
It returns the value associated with given key; Returns null if the key does
not exist.
5 Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
6 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
7 boolean isEmpty( )
It returns true if dictionary has no elements; otherwise returns false.
8 int size( )
It returns the total number of elements in the dictionary.

Example
import java.util.*;

public class DictionaryExample {

public static void main(String args[]) {

Dictionary dict = new Hashtable();

dict.put(1, "Rama");
dict.put(2, "Seetha");
dict.put(3, "Heyansh");
dict.put(4, "Varshith");
dict.put(5, "Manutej");

System.out.println("Dictionary\n=> " + dict);


// keys()
System.out.print("\nKeys in Dictionary\n=> ");
for (Enumeration i = dict.keys(); i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}

// elements()
System.out.print("\n\nValues in Dictionary\n=> ");
for (Enumeration i = dict.elements(); i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}

//get()
System.out.println("\n\nValue associated with key 3 => " + dict.get(3));
System.out.println("Value associated with key 30 => " + dict.get(30));

//size()
System.out.println("\nDictionary has " + dict.size() + " elements");

//isEmpty()
System.out.println("\nIs Dictionary empty? " + dict.isEmpty());
}
}

Hashtable class

In java, the package java.util contains a class called Hashtable which works like a HashMap but
it is synchronized. The Hashtable is a concrete class of Dictionary. It is used to store and manage
elements in the form of a pair of key and value.

The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates with
a value. Any non-null object can be used as a key or as a value. We can use the key to retrieve
the value back when needed.

 The Hashtable class is a concrete class of Dictionary.

 The Hashtable class is synchronized.

 The Hashtable does no allow null key or value.


 The Hashtable has the initial default capacity 11.

Example
import java.util.*;

public class HashtableExample {

public static void main(String[] args) {

Random num = new Random();


Hashtable table = new Hashtable();

//put(key, value)
for(int i = 1; i <= 5; i++)
table.put(i, num.nextInt(100));

System.out.println("Hashtable => " + table);

//get(key)
System.out.println("\nValue associated with key 3 => " + table.get(3));
System.out.println("Value associated with key 30 => " + table.get(30));

//keySet()
System.out.println("\nKeys => " + table.keySet());

//values()
System.out.println("\nValues => " + table.values());

//entrySet()
System.out.println("\nKey, Value pairs as a set => " + table.entrySet());

//hashCode()
System.out.println("\nHash code => " + table.hashCode());

//hashCode()
System.out.println("\nTotal number of elements => " + table.size());

//isEmpty()
System.out.println("\nEmpty status of Hashtable => " + table.isEmpty());
}
}
Properties class

In java, the package java.util contains a class called Properties which is a child class of Hashtable
class. Java has this built-in class Properties which allow us to save and load multiple values from
a file. This makes the class extremely useful for accessing data related to configuration.

 🔔 The Properties class is child class of Hashtable class.

 🔔 The Properties class used to store configuration values.

 🔔 The Properties class stores the data as key, value pairs.

 🔔 In Properties class both key and value are String data type.

 🔔 Using Properties class, we can load key, value pairs into a Properties object from a
stream.

 🔔 Using Properties class, we can save the Properties object to a stream.


Methods of properties class:
 void store(OutputStream os, String comment)It writes the properties in the
OutputStream object.
 String getProperty(String key)It returns value associated with the specified key.
 void setProperty(String key, String value)It calls the put method of Hashtable.

Example

import java.io.*;

import java.util.*;

public class PropertiesClassExample {

public static void main(String[] args) {

FileOutputStream fos = null;

File configFile = null;

try {

configFile = new File("config.properties");

fos = new FileOutputStream(configFile);


Properties configProperties = new Properties();

configProperties.setProperty("userName", "btechsmartclass");

configProperties.setProperty("password", "java");

configProperties.setProperty("email", "[email protected]");

configProperties.store(fos, "Login Details");

fos.close();

System.out.println("Configuration saved!!!");

catch(Exception e) {

System.out.println("Something went wrong while opening file");

}
Stack class
In java, the package java.util contains a class called Stack which is a child class of Vector class. It
implements the standard principle Last-In-First-Out of stack data structure.

The Stack has push method for inesrtion and pop method for deletion. It also has other utility methods.

In Stack, the elements are added to the top of the stack and removed from the top of the stack.

The Stack class in java has the following methods.

S.No. Methods with Description

1 Object push(Object element)

It pushes the element onto the stack and returns the same.

2 Object pop( )
S.No. Methods with Description

It returns the element on the top of the stack and removes the same.

3 int search(Object element)

If element found, it returns offset from the top. Otherwise, -1 is returned.

4 Object peek( )

It returns the element on the top of the stack.

5 boolean empty()

It returns true if the stack is empty, otherwise returns false.

Example

import java.util.*;

public class StackClassExample {

public static void main(String[] args) {

Stack stack = new Stack();

Random num = new Random();

for(int i = 0; i < 5; i++)

stack.push(num.nextInt(100));

System.out.println("Stack elements => " + stack);

System.out.println("Top element is " + stack.peek());

System.out.println("Removed element is " + stack.pop());

System.out.println("Element 50 availability => " + stack.search(50));

System.out.println("Stack is empty? - " + stack.isEmpty());

}
Vector class
In java, the package java.util contains a class called Vector which implements the List interface.

The Vector is similar to an ArrayList. Like ArrayList Vector also maintains the insertion order. But Vector
is synchronized, due to this reason, it is rarly used in the non-thread application. It also lead to poor
performance.

 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.

Methods with Description

boolean add(Object o)

It appends the specified element to the end of this Vector.

void add(int index, Object element)


It inserts the specified element at the specified position in this Vector.

void addElement(Object obj)


Adds the specified object to the end of the vector, increasing its size by one.

Object get(int index)


It returns the element at specified index in the Vector.
Object firstElement()
It returns the first element of the Vector.
int indexOf(Object element)
It returns the index value of the first occurence of the given element in the
Vector.
int capacity()
It returns the current capacity of the Vector.
boolean contains(Object element)
It returns true if element found in the Vector, otherwise returns false.
int size()
It returns total number of elements in the vector.
boolean isEmpty()
It returns true if Vector has no elements, otherwise returns false.

Example
import java.util.*;
public class VectorClassExample {
public static void main(String[] args) {
Vector list = new Vector();
list.add(10);
list.add(30);
list.add(0, 100);
list.addElement(50);
System.out.println("Vector => " + list);
System.out.println("get(2) => " + list.get(2));
System.out.println("firstElement() => " + list.firstElement());
System.out.println("indexOf(50) => " + list.indexOf(50));

System.out.println("contains(30) => " + list.contains(30));


System.out.println("capacity() => " + list.capacity());
System.out.println("size() => " + list.size());
System.out.println("isEmpty() => " + list.isEmpty());

}
Other Utility classes in java

StringTokenizer class

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.
Methods of the StringTokenizer Class

The six useful methods of the StringTokenizer class are as follows:

Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

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

String nextToken(String delim) It returns the next token based on the delimiter.

boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

Example program:
import java.util.StringTokenizer;
public class Simple{

public static void main(String args[]){

StringTokenizer st = new StringTokenizer("my name is akshara"," ");

while (st.hasMoreTokens()) {

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

Output:

my
name
is
akshara

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.

Methods with Description


void and(BitSet bitSet)
It performs AND operation on the contents of the invoking BitSet object with
Methods with Description
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 objects 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.
int length( )
It returns the total number of bits in the invoking BitSet.
int size( )
It returns the total number of bits in the invoking BitSet.
boolean get(int index)
It retruns the present state of the bit at given index in the invoking BitSet.
void set(int index)
It sets the bit specified by index.

Example
import java.util.*;

public class BitSetClassExample {

public static void main(String[] args) {

BitSet bSet_1 = new BitSet();


BitSet bSet_2 = new BitSet(16);

bSet_1.set(10);
bSet_1.set(5);
bSet_1.set(0);
bSet_1.set(7);
bSet_1.set(20);

bSet_2.set(1);
bSet_2.set(15);
bSet_2.set(20);
bSet_2.set(77);
bSet_2.set(50);

System.out.println("BitSet_1 => " + bSet_1);


System.out.println("BitSet_2 => " + bSet_2);

bSet_1.and(bSet_2);
System.out.println("BitSet_1 after and with bSet_2 => " + bSet_1);

bSet_1.andNot(bSet_2);
System.out.println("BitSet_1 after andNot with bSet_2 => " + bSet_1);

System.out.println("Length of the bSet_2 => " + bSet_2.length());


System.out.println("Size of the bSet_2 => " + bSet_2.size());

System.out.println("Bit at index 2 in bSet_2 => " + bSet_2.get(2));

bSet_2.set(2);
System.out.println("Bit at index 2 after set in bSet_2 => " + bSet_2.get(2));
}
}

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.

Methods with Description


long getTime()
It returns the time represented by this date object.
void setTime(long time)
It changes the current date and time to given time.
int hashCode()
It returns the hash code value of the invoking 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.
Example
import java.time.Instant;
import java.util.Date;

public class DateClassExample {

public static void main(String[] args) {

Date time = new Date();

System.out.println("Current date => " + time);

System.out.println("Date => " + time.getTime() + " milliseconds");

System.out.println("after() => " + time.after(time) + " milliseconds");

System.out.println("before() => " + time.before(time) + " milliseconds");

System.out.println("hashCode() => " + time.hashCode());

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.

Methods with Description


Date getTime()
Methods with Description
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 get(int field)
It rerturns the value for the given calendar field.
int getFirstDayOfWeek()
It returns the day of the week in integer form.
long getTimeInMillis()
It returns the current time in millisecond.
int hashCode()
It returns the hash code of the invoking object.

Example
import java.util.*;
public class CalendarClassExample {
public static void main(String[] args) {

Calendar cal = Calendar.getInstance();

System.out.println("Current date and time : \n=>" + cal);


System.out.println("Current Calendar type : " + cal.getCalendarType());
System.out.println("Current date and time : \n=>" + cal.getTime());
System.out.println("Current date time zone : \n=>" + cal.getTimeZone());
System.out.println("Calendar filed 1 (year): " + cal.get(1));
System.out.println("Calendar day in integer form: " + cal.getFirstDayOfWeek());
System.out.println("Calendar weeks in a year: " + cal.getWeeksInWeekYear());
System.out.println("Time in milliseconds: " + cal.getTimeInMillis());
System.out.println("Calendar hash code: " + cal.hashCode());

}
}

Random class:
We can generate random numbers in Java using the Random class of Java.util package.
Using this Random class, we can generate a random number of the types integer, float,
double, long, and boolean. We have to follow below-mentioned steps to generate a
number using the Random class.
 First, we have to import Java.util.Random class
 Second, create an object of Random class
 Invoke any of the following methods:
Methods with Description

Boolean nextBoolean()
It generates the next uniformly distributed pseudo-random boolean value.

double nextDouble()
It generates the next pseudo-random double number between 0.0 and 1.0.

float nextFloat()
It generates the next pseudo-random float number between 0.0 and 1.0..

int nextInt(int n)
It generates the next pseudo-random integer value between zero and n.

long nextLong()
It generates the next pseudo-random, uniformly distributed long value.

.
Example

import java.util.Random;
public class RandomClassExample {
public static void main(String[] args) {
Random rand = new Random();

System.out.println("Integer random number - " + rand.nextInt());


System.out.println("Integer random number from 0 to 100 - " + rand.nextInt(100));
System.out.println("Boolean random value - " + rand.nextBoolean());
System.out.println("Double random number - " + rand.nextDouble());
System.out.println("Float random number - " + rand.nextFloat());
System.out.println("Long random number - " + rand.nextLong());
}

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.
S.No. Methods with Description

1 Formatter format(Locale l, String format, Object...


args)
It writes a formatted string to the invoking object's
destination using the specified locale, format string, and
arguments.

2 Formatter format(String format, Object... args)


It writes a formatted string to the invoking object's
destination using the specified format string and arguments.

3 Locale locale()
It returns the locale set by the construction of the
invoking formatter.

Example

import java.util.*;
public class FormatterClassExample {
public static void main(String[] args) {
Formatter formatter=new Formatter();

formatter = new Formatter();


formatter.format(Locale.FRANCE,"%.5f", -1325.789);
System.out.println(formatter);

String name = "Java";


formatter = new Formatter();
formatter.format(Locale.US,"Hello %s !", name);
System.out.println("" + formatter + " " + formatter.locale());

formatter = new Formatter();


formatter.format("%.4f", 123.1234567);
System.out.println("Decimal floating-point notation to 4 places: " + formatter);

formatter = new Formatter();


formatter.format("%010d", 88);
System.out.println("value in 10 digits: " + formatter);
}
}

Output :
-1325,78900
Hello Java
Decimal floating-point notation to 4 places:123.1235
value in 10 digits:0000000088

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 provides various methods that allow us to read inputs of different types.

Method Description

nextInt() reads an int value from the user

nextFloat() reads a float value form the user

nextBoolean() reads a boolean value from the user

nextLine() reads a line of text from the user

next() reads a word from the user

nextByte() reads a byte value from the user

nextDouble() reads a double value from the user

nextShort() reads a short value from the user

nextLong() reads a long value from the user

Example program:

import java.util.Scanner;
public class ScannerClassExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in); // Input stream is used

System.out.print("Enter any name: ");

String name = read.next();

System.out.print("Enter your age in years: ");

int age = read.nextInt();

System.out.print("Enter your salary: ");

double salary = read.nextDouble();

System.out.print("Enter any message: ");

read = new Scanner(System.in);

String msg = read.nextLine();

System.out.println("\n------------------------------------------");

System.out.println("Hello, " + name);

System.out.println("You are " + age + " years old.");

System.out.println("You are earning Rs." + salary + " per month.");

System.out.println("Words from " + name + " - " + msg);

}}

You might also like