[Go to site: main page, start]

0% found this document useful (0 votes)
3 views92 pages

Java Vector Class Overview and Methods

Java Vector is a dynamic array that can grow or shrink in size, part of the Java Collection framework since version 1.2, and implements the List interface. It is synchronized and thread-safe, but it is recommended to use ArrayList for better performance when thread safety is not required. The Vector class provides various methods for manipulating elements, including adding, removing, and accessing elements, as well as constructors for different initial capacities.

Uploaded by

Prabin Magar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views92 pages

Java Vector Class Overview and Methods

Java Vector is a dynamic array that can grow or shrink in size, part of the Java Collection framework since version 1.2, and implements the List interface. It is synchronized and thread-safe, but it is recommended to use ArrayList for better performance when thread safety is not required. The Vector class provides various methods for manipulating elements, including adding, removing, and accessing elements, as well as constructors for different initial capacities.

Uploaded by

Prabin Magar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Vector

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of
elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in
the [Link] package and implements the List interface, so we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the
thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and throws
the ConcurrentModificationException.

It is similar to the ArrayList, but with two differences-

Vector is synchronized.

Java Vector contains many legacy methods that are not the part of a collections framework.

Java Vector class Declaration

public class Vector<E>

extends Object<E>

implements List<E>, Cloneable, Serializable

Java Vector Constructors - Vector class supports four types of constructors. These are given below:

S Constructor Description
N
1) vector() It constructs an empty vector with the default size as 10.
2) vector(int initialCapacity) It constructs an empty vector with the specified initial capacity and
with its capacity increment equal to zero.
3) vector(int initialCapacity, int It constructs an empty vector with the specified initial capacity and
capacityIncrement) capacity increment.
4) Vector( Collection<? extends It constructs a vector that contains the elements of a collection c.
E> c)

Java Vector Methods - The following are the list of Vector class methods:

S Method Description
N
1) add() It is used to append the specified element in the given vector.
2) addAll() It is used to append all of the elements in the specified collection to the end of this
Vector.
3) addElement() It is used to append the specified component to the end of this vector. It increases
the vector size by one.
4) capacity() It is used to get the current capacity of this vector.
5) clear() It is used to delete all of the elements from this vector.
6) clone() It returns a clone of this vector.
7) contains() It returns true if the vector contains the specified element.
8) containsAll() It returns true if the vector contains all of the elements in the specified collection.
9) copyInto() It is used to copy the components of the vector into the specified array.
10 elementAt() It is used to get the component at the specified index.
)
11 elements() It returns an enumeration of the components of a vector.
)
12 ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It
) ensures that the vector can hold at least the number of components specified by
the minimum capacity argument.
13 equals() It is used to compare the specified object with the vector for equality.
)
14 firstElement() It is used to get the first component of the vector.
)
15 forEach() It is used to perform the given action for each element of the Iterable until all
) elements have been processed or the action throws an exception.
16 get() It is used to get an element at the specified position in the vector.
)
17 hashCode() It is used to get the hash code value of a vector.
)
18 indexOf() It is used to get the index of the first occurrence of the specified element in the
) vector. It returns -1 if the vector does not contain the element.
19 insertElementAt() It is used to insert the specified object as a component in the given vector at the
) specified index.
20 isEmpty() It is used to check if this vector has no components.
)
21 iterator() It is used to get an iterator over the elements in the list in proper sequence.
)
22 lastElement() It is used to get the last component of the vector.
)
23 lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
) vector. It returns -1 if the vector does not contain the element.
24 listIterator() It is used to get a list iterator over the elements in the list in proper sequence.
)
25 remove() It is used to remove the specified element from the vector. If the vector does not
) contain the element, it is unchanged.
26 removeAll() It is used to delete all the elements from the vector that are present in the
) specified collection.
27 removeAllElemen It is used to remove all elements from the vector and set the size of the vector to
) ts() zero.
28 removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from the
) vector.
29 removeElementAt It is used to delete the component at the specified index.
) ()
30 removeIf() It is used to remove all of the elements of the collection that satisfy the given
) predicate.
31 removeRange() It is used to delete all of the elements from the vector whose index is between
) fromIndex, inclusive and toIndex, exclusive.
32 replaceAll() It is used to replace each element of the list with the result of applying the
) operator to that element.
33 retainAll() It is used to retain only that element in the vector which is contained in the
) specified collection.
34 set() It is used to replace the element at the specified position in the vector with the
) specified element.
35 setElementAt() It is used to set the component at the specified index of the vector to the specified
) object.
36 setSize() It is used to set the size of the given vector.
)
37 size() It is used to get the number of components in the given vector.
)
38 sort() It is used to sort the list according to the order induced by the specified
) Comparator.
39 spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the
) list.
40 subList() It is used to get a view of the portion of the list between fromIndex, inclusive, and
) toIndex, exclusive.
41 toArray() It is used to get an array containing all of the elements in this vector in correct
) order.
42 toString() It is used to get a string representation of the vector.
)
43 trimToSize() It is used to trim the capacity of the vector to the vector's current size.
)

Java Vector Example


import [Link].*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
[Link]("Tiger");
[Link]("Lion");
[Link]("Dog");
[Link]("Elephant");
//Adding elements using addElement() method of Vector
[Link]("Rat");
[Link]("Cat");
[Link]("Deer");
[Link]("Elements are: "+vec);
}
}

Output:

Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Java Vector Example 2

import [Link].*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
[Link]("Tiger");
[Link]("Lion");
[Link]("Dog");
[Link]("Elephant");
//Check size and capacity
[Link]("Size is: "+[Link]());
[Link]("Default capacity is: "+[Link]());
//Display Vector elements
[Link]("Vector element is: "+vec);
[Link]("Rat");
[Link]("Cat");
[Link]("Deer");
//Again check size and capacity after two insertions
[Link]("Size after addition: "+[Link]());
[Link]("Capacity after addition is: "+[Link]());
//Display Vector elements again
[Link]("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if([Link]("Tiger"))
{
[Link]("Tiger is present at the index " +[Link]("Tiger"));
}
else
{
[Link]("Tiger is not present in the list.");
}
//Get the first element
[Link]("The first animal of the vector is = "+[Link]());
//Get the last element
[Link]("The last animal of the vector is = "+[Link]());
}
}

Output:

Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

Java Vector Example 3

import [Link].*;
public class VectorExample2 {
public static void main(String args[]) {
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
[Link](100);
[Link](200);
[Link](300);
[Link](200);
[Link](400);
[Link](500);
[Link](600);
[Link](700);
//Display the vector elements
[Link]("Values in vector: " +in);
//use remove() method to delete the first occurence of an element
[Link]("Remove first occourence of element 200: "+[Link]((Integer)200)
);
//Display the vector elements afre remove() method
[Link]("Values in vector: " +in);
//Remove the element at index 4
[Link]("Remove element at index 4: " +[Link](4));
[Link]("New Value list in vector: " +in);
//Remove an element
[Link](5);
//Checking vector and displays the element
[Link]("Vector element after removal: " +in);
//Get the hashcode for this vector
[Link]("Hash code of this vector = "+[Link]());
//Get the element at specified index
[Link]("Element at index 1 is = "+[Link](1));
}
}

Output:

Values in vector: [100, 200, 300, 200, 400, 500, 600, 700]
Remove first occourence of element 200: true
Values in vector: [100, 300, 200, 400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300, 200, 400, 600, 700]
Vector element after removal: [100, 300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300

Collections in Java

The Collection in Java is a framework that provides an architecture to store and manipulate the group of
objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List,
Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java - A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

It provides readymade architecture.

It represents a set of classes and interfaces.

It is optional.

What is Collection framework - The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:

Interfaces and its implementations, i.e., classes

Algorithm

Do You Know?

What are the two ways to iterate the elements of a collection?

What is the difference between ArrayList and LinkedList classes in collection framework?

What is the difference between ArrayList and Vector classes in collection framework?

What is the difference between HashSet and HashMap classes in collection framework?

What is the difference between HashMap and Hashtable class?

What is the difference between Iterator and Enumeration interface in collection framework?

How can we sort the elements of an object? What is the difference between Comparable and Comparator
interfaces?

What does the hashcode() method?

What is the difference between Java collection and Java collections?

Hierarchy of Collection Framework - Let us see the hierarchy of Collection framework.


The [Link] package contains all the classes and interfaces for the Collection framework.
Methods of Collection interface - There are many methods declared in the Collection interface. They are as
follows:

No Method Description
.
1 public boolean add(E e) It is used to insert an element in this collection.
2 public boolean It is used to insert the specified collection elements in the
addAll(Collection<? invoking collection.
extends E> c)
3 public boolean It is used to delete an element from the collection.
remove(Object element)
4 public boolean It is used to delete all the elements of the specified
removeAll(Collection<?> collection from the invoking collection.
c)
5 default boolean It is used to delete all the elements of the collection that
removeIf(Predicate<? satisfy the specified predicate.
super E> filter)
6 public boolean It is used to delete all the elements of invoking collection
retainAll(Collection<?> c) except the specified collection.
7 public int size() It returns the total number of elements in the collection.
8 public void clear() It removes the total number of elements from the collection.
9 public boolean It is used to search an element.
contains(Object element)
10 public boolean It is used to search the specified collection in the collection.
containsAll(Collection<?>
c)
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts collection into array.
13 public <T> T[] toArray(T[] It converts collection into array. Here, the runtime type of
a) the returned array is that of the specified array.
14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> It returns a possibly parallel Stream with the collection as its
parallelStream() source.
16 default Stream<E> It returns a sequential Stream with the collection as its
stream() source.
17 default Spliterator<E> It generates a Spliterator over the specified elements in the
spliterator() collection.
18 public boolean It matches two collections.
equals(Object element)
19 public int hashCode() It returns the hash code number of the collection.

Iterator interface

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

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

No Method Description
.
1 public boolean It returns true if the iterator has more
hasNext() elements otherwise it returns false.
2 public Object It returns the element and moves the
next() cursor pointer to the next element.
3 public void It removes the last elements returned
remove() by the iterator. It is less used.

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

It contains only one abstract method. i.e.,

Iterator<T> iterator()

It returns the iterator over the elements of type T.

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

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

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

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

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

List <data-type> list2 = new LinkedList();

List <data-type> list3 = new Vector();

List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the elements from
the list.

The classes that implement the List interface are given below.
ArrayList - The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The
elements stored in the ArrayList class can be randomly accessed. Consider the following example.

import [Link].*;

class TestJavaCollection1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

[Link]("Ravi");//Adding object in arraylist

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

//Traversing list through Iterator

Iterator itr=[Link]();

while([Link]()){

[Link]([Link]());

Output:

Ravi

Vijay

Ravi

Ajay

LinkedList - LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized. In
LinkedList, the manipulation is fast because no shifting is required.

Consider the following example.

import [Link].*;

public class TestJavaCollection2{

public static void main(String args[]){

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

Iterator<String> itr=[Link]();
while([Link]()){

[Link]([Link]());

Output:

Ravi

Vijay

Ravi

Ajay

Vector - Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not the part of Collection framework. Consider the following
example.

import [Link].*;

public class TestJavaCollection3{

public static void main(String args[]){

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

[Link]("Ayush");

[Link]("Amit");

[Link]("Ashish");

[Link]("Garima");

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Output:

Ayush

Amit

Ashish

Garima

Stack - The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The
stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean
peek(), boolean push(object o), which defines its properties. Consider the following example.

import [Link].*;
public class TestJavaCollection4{

public static void main(String args[]){

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

[Link]("Ayush");

[Link]("Garvit");

[Link]("Amit");

[Link]("Ashish");

[Link]("Garima");

[Link]();

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Output:

Ayush

Garvit

Amit

Ashish

Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold
the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and
ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:

Queue<String> q1 = new PriorityQueue();

Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be
processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

Consider the following example.

import [Link].*;

public class TestJavaCollection5{

public static void main(String args[]){


PriorityQueue<String> queue=new PriorityQueue<String>();

[Link]("Amit Sharma");

[Link]("Vijay Raj");

[Link]("JaiShankar");

[Link]("Raj");

[Link]("head:"+[Link]());

[Link]("head:"+[Link]());

[Link]("iterating the queue elements:");

Iterator itr=[Link]();

while([Link]()){

[Link]([Link]());

[Link]();

[Link]();

[Link]("after removing two elements:");

Iterator<String> itr2=[Link]();

while([Link]()){

[Link]([Link]());

Output:

head:Amit Sharma

head:Amit Sharma

iterating the queue elements:

Amit Sharma

Raj

JaiShankar

Vijay Raj

after removing two elements:

Raj

Vijay Raj

Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the
side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.

Deque can be instantiated as:

Deque d = new ArrayDeque();

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add
or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

import [Link].*;

public class TestJavaCollection6{

public static void main(String[] args) {

//Creating Deque and adding elements

Deque<String> deque = new ArrayDeque<String>();

[Link]("Gautam");

[Link]("Karan");

[Link]("Ajay");

//Traversing elements

for (String str : deque) {

[Link](str);

Output:

Gautam

Karan

Ajay

Set Interface

Set Interface in Java is present in [Link] package. It extends the Collection interface. It represents the
unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null
value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();

Set<data-type> s2 = new LinkedHashSet<data-type>();

Set<data-type> s3 = new TreeSet<data-type>();

HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing
is used to store the elements in the HashSet. It contains unique items. Consider the following example.

import [Link].*;

public class TestJavaCollection7{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet<String>();

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

//Traversing elements

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Output:

Vijay

Ravi

Ajay

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class
and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order
and permits null elements.

Consider the following example.

import [Link].*;

public class TestJavaCollection8{

public static void main(String args[]){

LinkedHashSet<String> set=new LinkedHashSet<String>();

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");
Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Output:

Ravi

Vijay

Ajay

SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the
SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional methods
that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet<data-type> set = new TreeSet();

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also
contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in
TreeSet stored in ascending order.

Consider the following example:

import [Link].*;

public class TestJavaCollection9{

public static void main(String args[]){

//Creating and adding elements

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

//traversing elements

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

}
}

Output:

Ajay

Ravi

Vijay

Java ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit. We can add or remove elements anytime. So, it is much
more flexible than the traditional array. It is found in the [Link] package. It is like
the Vector in C++.

The ArrayList in Java can have the duplicate elements also. It implements the List
interface so we can use all the methods of List interface here. The ArrayList maintains
the insertion order internally.

It inherits the AbstractList class and implements List interface.

The important points about Java ArrayList class are:

Java ArrayList class can contain duplicate elements.

Java ArrayList class maintains insertion order.

Java ArrayList class is non-synchronized.

Java ArrayList allows random access because array works at the index basis.

In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot
of shifting needs to occur if any element is removed from the array list.

Hierarchy of ArrayList class

As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List
interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let's see the declaration for [Link] class.

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Seriali
zable

Constructors of ArrayList

Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the collec
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

Methods of ArrayList

Method Description

void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? extends E> It is used to append all of the elements in the specified collection to the end o
c) order that they are returned by the specified collection's iterator.

boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection, starting a
extends E> c) position of the list.

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

void ensureCapacity(int It is used to enhance the capacity of an ArrayList instance.


requiredCapacity)

E get(int index) It is used to fetch the element from the particular position of the list.

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

Iterator()

listIterator()

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified
if the list does not contain this element.

Object[] toArray() It is used to return an array containing all of the elements in this list in the cor

<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in the cor

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

boolean contains(Object o) It returns true if the list contains the specified element

int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified
if the List does not contain this element.

E remove(int index) It is used to remove the element present at the specified position in the list.

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

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that satisfies the given pred
filter)

protected void removeRange(int It is used to remove all the elements lies within the given range.
fromIndex, int toIndex)

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the specified element.
operator)

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the specified

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

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of specified comparator.

Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.

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

int size() It is used to return the number of elements present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list's current

Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so
typecasting is not required at runtime.

Let's see the old non-generic example of creating java collection.

ArrayList list=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified
type of objects in it. If you try to add another type of object, it gives compile time error.

For more information on Java generics, click here Java Generics Tutorial.

Java ArrayList Example

import [Link].*;

public class ArrayListExample1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist


[Link]("Mango");//Adding object in arraylist

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//Printing the arraylist object

[Link](list);

Test it Now

Output:

[Mango, Apple, Banana, Grapes]

Iterating ArrayList using Iterator

Let's see an example to traverse ArrayList elements using the Iterator interface.

import [Link].*;

public class ArrayListExample2{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

[Link]("Mango");//Adding object in arraylist

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//Traversing list through Iterator

Iterator itr=[Link]();//getting the Iterator

while([Link]()){//check if iterator has the elements

[Link]([Link]());//printing the element and move to next

Test it Now

Output:

Mango

Apple

Banana

Grapes
Iterating ArrayList using For-each loop

Let's see an example to traverse the ArrayList elements using the for-each loop

import [Link].*;

public class ArrayListExample3{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

[Link]("Mango");//Adding object in arraylist

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//Traversing list through for-each loop

for(String fruit:list)

[Link](fruit);

Output:

Test it Now

Mango

Apple

Banana

Grapes

Get and Set ArrayList

The get() method returns the element at the specified index, whereas the set() method changes the element.

import [Link].*;

public class ArrayListExample4{

public static void main(String args[]){

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

[Link]("Mango");

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//accessing the element


[Link]("Returning element: "+[Link](1));//it will return the 2nd element, because index starts fro
m0

//changing the element

[Link](1,"Dates");

//Traversing list

for(String fruit:al)

[Link](fruit);

Test it Now

Output:

Returning element: Apple

Mango

Dates

Banana

Grapes

How to Sort ArrayList

The [Link] package provides a utility class Collections which has the static method sort(). Using
the [Link]() method, we can easily sort the ArrayList.

import [Link].*;

class SortArrayList{

public static void main(String args[]){

//Creating a list of fruits

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

[Link]("Mango");

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//Sorting the list

[Link](list1);

//Traversing list through the for-each loop

for(String fruit:list1)

[Link](fruit);
[Link]("Sorting numbers...");

//Creating a list of numbers

List<Integer> list2=new ArrayList<Integer>();

[Link](21);

[Link](11);

[Link](51);

[Link](1);

//Sorting the list

[Link](list2);

//Traversing list through the for-each loop

for(Integer number:list2)

[Link](number);

Output:

Apple

Banana

Grapes

Mango

Sorting numbers...

11

21

51

Ways to iterate the elements of the collection in Java

There are various ways to traverse the collection elements:

By Iterator interface.

By for-each loop.

By ListIterator interface.

By for loop.

By forEach() method.

By forEachRemaining() method.
Iterating Collection through remaining ways

Let's see an example to traverse the ArrayList elements through other ways

import [Link].*;

class ArrayList4{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

[Link]("Ravi");//Adding object in arraylist

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

[Link]("Traversing list through List Iterator:");

//Here, element iterates in reverse order

ListIterator<String> list1=[Link]([Link]());

while([Link]())

String str=[Link]();

[Link](str);

[Link]("Traversing list through for loop:");

for(int i=0;i<[Link]();i++)

[Link]([Link](i));

[Link]("Traversing list through forEach() method:");

//The forEach() method is a new feature, introduced in Java 8.

[Link](a->{ //Here, we are using lambda expression

[Link](a);

});

[Link]("Traversing list through forEachRemaining() method:");

Iterator<String> itr=[Link]();

[Link](a-> //Here, we are using lambda expression


{

[Link](a);

});

Output:

Traversing list through List Iterator:

Ajay

Ravi

Vijay

Ravi

Traversing list through for loop:

Ravi

Vijay

Ravi

Ajay

Traversing list through forEach() method:

Ravi

Vijay

Ravi

Ajay

Traversing list through forEachRemaining() method:

Ravi

Vijay

Ravi

Ajay

User-defined class objects in Java ArrayList

Let's see an example where we are storing Student class object in an array list.

class Student{

int rollno;

String name;

int age;
Student(int rollno,String name,int age){

[Link]=rollno;

[Link]=name;

[Link]=age;

import [Link].*;

class ArrayList5{

public static void main(String args[]){

//Creating user-defined class objects

Student s1=new Student(101,"Sonoo",23);

Student s2=new Student(102,"Ravi",21);

Student s2=new Student(103,"Hanumat",25);

//creating arraylist

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

[Link](s1);//adding Student class object

[Link](s2);

[Link](s3);

//Getting Iterator

Iterator itr=[Link]();

//traversing elements of ArrayList object

while([Link]()){

Student st=(Student)[Link]();

[Link]([Link]+" "+[Link]+" "+[Link]);

Output:

101 Sonoo 23

102 Ravi 21

103 Hanumat 25

Java ArrayList Serialization and Deserialization Example


Let's see an example to serialize an ArrayList object and then deserialize it.

import [Link].*;

import [Link].*;

class ArrayList6 {

public static void main(String [] args)

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

try

//Serialization

FileOutputStream fos=new FileOutputStream("file");

ObjectOutputStream oos=new ObjectOutputStream(fos);

[Link](al);

[Link]();

[Link]();

//Deserialization

FileInputStream fis=new FileInputStream("file");

ObjectInputStream ois=new ObjectInputStream(fis);

ArrayList list=(ArrayList)[Link]();

[Link](list);

}catch(Exception e)

[Link](e);

Output:

[Ravi, Vijay, Ajay]


Java ArrayList example to add elements

Here, we see different ways to add an element.

import [Link].*;

class ArrayList7{

public static void main(String args[]){

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

[Link]("Initial list of elements: "+al);

//Adding elements to the end of the list

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

[Link]("After invoking add(E e) method: "+al);

//Adding an element at the specific position

[Link](1, "Gaurav");

[Link]("After invoking add(int index, E element) method: "+al);

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

[Link]("Sonoo");

[Link]("Hanumat");

//Adding second list elements to the first list

[Link](al2);

[Link]("After invoking addAll(Collection<? extends E> c) method: "+al);

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

[Link]("John");

[Link]("Rahul");

//Adding second list elements to the first list at specific position

[Link](1, al3);

[Link]("After invoking addAll(int index, Collection<? extends E> c) method: "+al);

Output:

Initial list of elements: []

After invoking add(E e) method: [Ravi, Vijay, Ajay]

After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:

[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

After invoking addAll(int index, Collection<? extends E> c) method:

[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

Java ArrayList example to remove elements

Here, we see different ways to remove an element.

import [Link].*;

class ArrayList8 {

public static void main(String [] args)

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

[Link]("Anuj");

[Link]("Gaurav");

[Link]("An initial list of elements: "+al);

//Removing specific element from arraylist

[Link]("Vijay");

[Link]("After invoking remove(object) method: "+al);

//Removing element on the basis of specific position

[Link](0);

[Link]("After invoking remove(index) method: "+al);

//Creating another arraylist

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

[Link]("Ravi");

[Link]("Hanumat");

//Adding new elements to arraylist

[Link](al2);

[Link]("Updated list : "+al);

//Removing all the new elements from arraylist


[Link](al2);

[Link]("After invoking removeAll() method: "+al);

//Removing elements on the basis of specified condition

[Link](str -> [Link]("Ajay")); //Here, we are using Lambda expression

[Link]("After invoking removeIf() method: "+al);

//Removing all the elements available in the list

[Link]();

[Link]("After invoking clear() method: "+al);

Output:

An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]

After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]

After invoking remove(index) method: [Ajay, Anuj, Gaurav]

Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]

After invoking removeAll() method: [Ajay, Anuj, Gaurav]

After invoking removeIf() method: [Anuj, Gaurav]

After invoking clear() method: []

Java ArrayList example of retainAll() method

import [Link].*;

class ArrayList9{

public static void main(String args[]){

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

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

[Link]("Ravi");

[Link]("Hanumat");

[Link](al2);

[Link]("iterating the elements after retaining the elements of al2");

Iterator itr=[Link]();

while([Link]()){
[Link]([Link]());

Output:

iterating the elements after retaining the elements of al2

Ravi

Java ArrayList example of isEmpty() method

import [Link].*;

class ArrayList10{

public static void main(String [] args)

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

[Link]("Is ArrayList Empty: "+[Link]());

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

[Link]("After Insertion");

[Link]("Is ArrayList Empty: "+[Link]());

Output:

Is ArrayList Empty: true

After Insertion

Is ArrayList Empty: false

Java ArrayList Example: Book

Let's see an ArrayList example where we are adding books to list and printing all the books.

import [Link].*;

class Book {

int id;

String name,author,publisher;

int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

public class ArrayListExample20 {

public static void main(String[] args) {

//Creating list of Books

List<Book> list=new ArrayList<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to list

[Link](b1);

[Link](b2);

[Link](b3);

//Traversing list

for(Book b:list){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

Test it Now

Output:

101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications and Networking Forouzan Mc Graw Hill 4

103 Operating System Galvin Wiley 6

Java LinkedList class


Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It
inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

Java LinkedList class can contain duplicate elements.

Java LinkedList class maintains insertion order.

Java LinkedList class is non synchronized.

In Java LinkedList class, manipulation is fast because no shifting needs to occur.

Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class

As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and implements List
and Deque interfaces.

Doubly Linked List

In the case of a doubly linked list, we can add or remove elements from both sides.

LinkedList class declaration

Let's see the declaration for [Link] class.

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneabl


e, Serializable
Constructors of Java LinkedList

Constructor Description

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

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

Methods of Java LinkedList

Method Description

boolean add(E e) It is used to append the specified element to the end of a list.

void add(int index, E element) It is used to insert the specified element at the specified position index in a list.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection to the end of
E> c) order that they are returned by the specified collection's iterator.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection to the end of
E> c) order that they are returned by the specified collection's iterator.

boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection, starting at the sp
extends E> c) of the list.

void addFirst(E e) It is used to insert the given element at the beginning of a list.

void addLast(E e) It is used to append the given element to the end of a list.

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

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

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

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

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

E get(int index) It is used to return the element at the specified position in a list.
E getFirst() It is used to return the first element in a list.

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

int indexOf(Object o) It is used to return the index in a list of the first occurrence of the specified elem
list does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the specified elem
list does not contain any element.

ListIterator<E> listIterator(int index) It is used to return a list-iterator of the elements in proper sequence, starting a
position in the list.

boolean offer(E e) It adds the specified element as the last element of a list.

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

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

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

E peekFirst() It retrieves the first element of a list or returns null if a list is empty.

E peekLast() It retrieves the last element of a list or returns null if a list is empty.

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

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

E pollLast() It retrieves and removes the last element of a list, or returns null if a list is empty

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

void push(E e) It pushes an element onto the stack represented by a list.

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

E remove(int index) It is used to remove the element at the specified position in a list.

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

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


boolean It is used to remove the first occurrence of the specified element in a list (when
removeFirstOccurrence(Object o) list from head to tail).

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

boolean It removes the last occurrence of the specified element in a list (when traversin
removeLastOccurrence(Object o) head to tail).

E set(int index, E element) It replaces the element at the specified position in a list with the specified elemen

Object[] toArray() It is used to return an array containing all the elements in a list in proper sequen
the last element).

<T> T[] toArray(T[] a) It returns an array containing all the elements in the proper sequence (from fi
element); the runtime type of the returned array is that of the specified array.

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

Java LinkedList Example

import [Link].*;

public class LinkedList1{

public static void main(String args[]){

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Output: Ravi
Vijay

Ravi

Ajay

Java LinkedList example to add elements

Here, we see different ways to add elements.

import [Link].*;

public class LinkedList2{

public static void main(String args[]){

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

[Link]("Initial list of elements: "+ll);

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

[Link]("After invoking add(E e) method: "+ll);

//Adding an element at the specific position

[Link](1, "Gaurav");

[Link]("After invoking add(int index, E element) method: "+ll);

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

[Link]("Sonoo");

[Link]("Hanumat");

//Adding second list elements to the first list

[Link](ll2);

[Link]("After invoking addAll(Collection<? extends E> c) method: "+ll);

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

[Link]("John");

[Link]("Rahul");

//Adding second list elements to the first list at specific position

[Link](1, ll3);

[Link]("After invoking addAll(int index, Collection<? extends E> c) method: "+ll);

//Adding an element at the first position

[Link]("Lokesh");

[Link]("After invoking addFirst(E e) method: "+ll);

//Adding an element at the last position


[Link]("Harsh");

[Link]("After invoking addLast(E e) method: "+ll);

Initial list of elements: []

After invoking add(E e) method: [Ravi, Vijay, Ajay]

After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]

After invoking addAll(Collection<? extends E> c) method:

[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

After invoking addAll(int index, Collection<? extends E> c) method:

[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

After invoking addFirst(E e) method:

[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

After invoking addLast(E e) method:

[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Java LinkedList example to remove elements

Here, we see different ways to remove an element.

import [Link].*;

public class LinkedList3 {

public static void main(String [] args)

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

[Link]("Anuj");

[Link]("Gaurav");

[Link]("Harsh");

[Link]("Virat");

[Link]("Gaurav");

[Link]("Harsh");
[Link]("Amit");

[Link]("Initial list of elements: "+ll);

//Removing specific element from arraylist

[Link]("Vijay");

[Link]("After invoking remove(object) method: "+ll);

//Removing element on the basis of specific position

[Link](0);

[Link]("After invoking remove(index) method: "+ll);

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

[Link]("Ravi");

[Link]("Hanumat");

// Adding new elements to arraylist

[Link](ll2);

[Link]("Updated list : "+ll);

//Removing all the new elements from arraylist

[Link](ll2);

[Link]("After invoking removeAll() method: "+ll);

//Removing first element from the list

[Link]();

[Link]("After invoking removeFirst() method: "+ll);

//Removing first element from the list

[Link]();

[Link]("After invoking removeLast() method: "+ll);

//Removing first occurrence of element from the list

[Link]("Gaurav");

[Link]("After invoking removeFirstOccurrence() method: "+ll);

//Removing last occurrence of element from the list

[Link]("Harsh");

[Link]("After invoking removeLastOccurrence() method: "+ll);

//Removing all the elements available in the list

[Link]();

[Link]("After invoking clear() method: "+ll);

}
}

Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]

After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]

After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]

After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]

After invoking clear() method: []

Java LinkedList Example to reverse a list of elements

import [Link].*;

public class LinkedList4{

public static void main(String args[]){

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

//Traversing the list of elements in reverse order

Iterator i=[Link]();

while([Link]())

[Link]([Link]());

Output: Ajay

Vijay

Ravi
Java LinkedList Example: Book

import [Link].*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

public class LinkedListExample {

public static void main(String[] args) {

//Creating list of Books

List<Book> list=new LinkedList<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to list

[Link](b1);

[Link](b2);

[Link](b3);

//Traversing list

for(Book b:list){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

Output:
101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications & Networking Forouzan Mc Graw Hill 4

103 Operating System Galvin Wiley 6

Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non
synchronized classes.

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

ArrayList LinkedList

1) ArrayList internally uses a dynamic array to store the elements. LinkedList internally uses a doubly linked li
elements.

2) Manipulation with ArrayList is slow because it internally uses an Manipulation with LinkedList is faster than Arra
array. If any element is removed from the array, all the bits are shifted uses a doubly linked list, so no bit shifting
in memory. memory.

3) An ArrayList class can act as a list only because it implements List LinkedList class can act as a list and queue b
only. implements List and Deque interfaces.

4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Java List

List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to
insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the
null elements in the list.

The List interface is found in the [Link] package and inherits the Collection interface. It is a factory of
ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The
implementation classes of List interface are ArrayList, LinkedList, Stack and Vector. The ArrayList and
LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.

List Interface declaration

public interface List<E> extends Collection<E>

Java List Methods

Method Description

void add(int index, E element) It is used to insert the specified element at the specified position in a list.

boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> It is used to append all of the elements in the specified collection to the end of
c)

boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection, starting at t
extends E> c) position of the list.

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

boolean equals(Object o) It is used to compare the specified object with the elements of a list.

int hashcode() It is used to return the hash code value for a list.

E get(int index) It is used to fetch the element from the particular position of the list.

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

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified e
1 if the list does not contain this element.

Object[] toArray() It is used to return an array containing all of the elements in this list in the corr

<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in the corr

boolean contains(Object o) It returns true if the list contains the specified element

boolean containsAll(Collection<?> c) It returns true if the list contains all the specified element

int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified
1 if the List does not contain this element.

E remove(int index) It is used to remove the element present at the specified position in the list.

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

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the specified element.
operator)
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the specified c

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

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of specified comparator.

Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.

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

int size() It is used to return the number of elements present in the list.

Java List vs ArrayList

List is an interface whereas ArrayList is the implementation class of List.

How to create List

The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to
create the List:

//Creating a List of type String using ArrayList

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

//Creating a List of type Integer using ArrayList

List<Integer> list=new ArrayList<Integer>();

//Creating a List of type Book using ArrayList

List<Book> list=new ArrayList<Book>();

//Creating a List of type String using LinkedList

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

In short, you can create the List of any type. The ArrayList<T> and LinkedList<T> classes are used to specify
the type. Here, T denotes the type.

Java List Example

Let's see a simple example of List where we are using the ArrayList class as the implementation.

import [Link].*;

public class ListExample1{

public static void main(String args[]){

//Creating a List
List<String> list=new ArrayList<String>();

//Adding elements in the List

[Link]("Mango");

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//Iterating the List element using for-each loop

for(String fruit:list)

[Link](fruit);

Test it Now

Output:

Mango

Apple

Banana

Grapes

How to convert Array to List

We can convert the Array to List by traversing the array and adding the element in list one by one using
[Link]() method. Let's see a simple example to convert array elements into List.

import [Link].*;

public class ArrayToListExample{

public static void main(String args[]){

//Creating Array

String[] array={"Java","Python","PHP","C++"};

[Link]("Printing Array: "+[Link](array));

//Converting Array to List

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

for(String lang:array){

[Link](lang);

[Link]("Printing List: "+list);


}

Test it Now

Output:

Printing Array: [Java, Python, PHP, C++]

Printing List: [Java, Python, PHP, C++]

How to convert List to Array

We can convert the List to Array by calling the [Link]() method. Let's see a simple example to convert list
elements into array.

import [Link].*;

public class ListToArrayExample{

public static void main(String args[]){

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

[Link]("Mango");

[Link]("Banana");

[Link]("Apple");

[Link]("Strawberry");

//Converting ArrayList to Array

String[] array = [Link](new String[[Link]()]);

[Link]("Printing Array: "+[Link](array));

[Link]("Printing List: "+fruitList);

Test it Now

Output:

Printing Array: [Mango, Banana, Apple, Strawberry]

Printing List: [Mango, Banana, Apple, Strawberry]

Get and Set Element in List

The get() method returns the element at the given index, whereas the set() method changes or replaces the
element.

import [Link].*;

public class ListExample2{

public static void main(String args[]){

//Creating a List

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


//Adding elements in the List

[Link]("Mango");

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//accessing the element

[Link]("Returning element: "+[Link](1));//it will return the 2nd element, because index starts fro
m0

//changing the element

[Link](1,"Dates");

//Iterating the List element using for-each loop

for(String fruit:list)

[Link](fruit);

Test it Now

Output:

Returning element: Apple

Mango

Dates

Banana

Grapes

How to Sort List

There are various ways to sort the List, here we are going to use [Link]() method to sort the list
element. The [Link] package provides a utility class Collections which has the static method sort(). Using
the [Link]() method, we can easily sort any List.

import [Link].*;

class SortArrayList{

public static void main(String args[]){

//Creating a list of fruits

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

[Link]("Mango");

[Link]("Apple");

[Link]("Banana");
[Link]("Grapes");

//Sorting the list

[Link](list1);

//Traversing list through the for-each loop

for(String fruit:list1)

[Link](fruit);

[Link]("Sorting numbers...");

//Creating a list of numbers

List<Integer> list2=new ArrayList<Integer>();

[Link](21);

[Link](11);

[Link](51);

[Link](1);

//Sorting the list

[Link](list2);

//Traversing list through the for-each loop

for(Integer number:list2)

[Link](number);

Output:

Apple

Banana

Grapes

Mango

Sorting numbers...

11

21

51

Java ListIterator Interface

ListIterator Interface is used to traverse the element in a backward and forward direction.
ListIterator Interface declaration

public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface:

Method Description

void add(E e) This method inserts the specified element into the list.

boolean hasNext() This method returns true if the list iterator has more elements while traversing the list in the forw

E next() This method returns the next element in the list and advances the cursor position.

int nextIndex() This method returns the index of the element that would be returned by a subsequent call to nex

boolean hasPrevious() This method returns true if this list iterator has more elements while traversing the list in the rev

E previous() This method returns the previous element in the list and moves the cursor position backward.

E previousIndex() This method returns the index of the element that would be returned by a subsequent call to pre

void remove() This method removes the last element from the list that was returned by next() or previous() met

void set(E e) This method replaces the last element returned by next() or previous() methods with the specifie

Example of ListIterator Interface

import [Link].*;

public class ListIteratorExample1{

public static void main(String args[]){

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

[Link]("Amit");

[Link]("Vijay");

[Link]("Kumar");

[Link](1,"Sachin");

ListIterator<String> itr=[Link]();

[Link]("Traversing elements in forward direction");

while([Link]()){

[Link]("index:"+[Link]()+" value:"+[Link]());
}

[Link]("Traversing elements in backward direction");

while([Link]()){

[Link]("index:"+[Link]()+" value:"+[Link]());

Output:

Traversing elements in forward direction

index:0 value:Amit

index:1 value:Sachin

index:2 value:Vijay

index:3 value:Kumar

Traversing elements in backward direction

index:3 value:Kumar

index:2 value:Vijay

index:1 value:Sachin

index:0 value:Amit

Example of List: Book

Let's see an example of List where we are adding the Books.

import [Link].*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

}
}

public class ListExample5 {

public static void main(String[] args) {

//Creating list of Books

List<Book> list=new ArrayList<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to list

[Link](b1);

[Link](b2);

[Link](b3);

//Traversing list

for(Book b:list){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

Test it Now

Output:

101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications and Networking Forouzan Mc Graw Hill 4

103 Operating System Galvin Wiley 6

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

The important points about Java HashSet class are:

HashSet stores the elements by using a mechanism called hashing.

HashSet contains unique elements only.

HashSet allows null value.

HashSet class is non synchronized.

HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.

HashSet is the best approach for search operations.

The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits
Collection and Iterable interfaces in hierarchical order.

HashSet class declaration

Let's see the declaration for [Link] class.

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java HashSet class


S Constructor Description
N

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

2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer value capacit
grows automatically as elements are added to the HashSet.

3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the given integer value ca
loadFactor) specified load factor.

4) HashSet(Collection<? It is used to initialize the hash set by using the elements of the collection c.
extends E> c)

Methods of Java HashSet class

Various methods of Java HashSet class are as follows:

S Modifier & Method Description


N Type

1) boolean add(E e) It is used to add the specified element to this set if it is not already present.

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

3) object clone() It is used to return a shallow copy of this HashSet instance: the elements
not cloned.

4) boolean contains(Object It is used to return true if this set contains the specified element.
o)

5) boolean isEmpty() It is used to return true if this set contains no elements.

6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.

7) boolean remove(Object It is used to remove the specified element from this set if it is present.
o)

8) int size() It is used to return the number of elements in the set.

9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements

Java HashSet Example

Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
import [Link].*;

class HashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet();

[Link]("One");

[Link]("Two");

[Link]("Three");

[Link]("Four");

[Link]("Five");

Iterator<String> i=[Link]();

while([Link]())

[Link]([Link]());

Five

One

Four

Two

Three

Java HashSet example ignoring duplicate elements

In this example, we see that HashSet doesn't allow duplicate elements.

import [Link].*;

class HashSet2{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet<String>();

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

//Traversing elements
Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Ajay

Vijay

Ravi

Java HashSet example to remove elements

Here, we see different ways to remove an element.

import [Link].*;

class HashSet3{

public static void main(String args[]){

HashSet<String> set=new HashSet<String>();

[Link]("Ravi");

[Link]("Vijay");

[Link]("Arun");

[Link]("Sumit");

[Link]("An initial list of elements: "+set);

//Removing specific element from HashSet

[Link]("Ravi");

[Link]("After invoking remove(object) method: "+set);

HashSet<String> set1=new HashSet<String>();

[Link]("Ajay");

[Link]("Gaurav");

[Link](set1);

[Link]("Updated List: "+set);

//Removing all the new elements from HashSet

[Link](set1);

[Link]("After invoking removeAll() method: "+set);

//Removing elements on the basis of specified condition

[Link](str->[Link]("Vijay"));

[Link]("After invoking removeIf() method: "+set);


//Removing all the elements available in the set

[Link]();

[Link]("After invoking clear() method: "+set);

An initial list of elements: [Vijay, Ravi, Arun, Sumit]

After invoking remove(object) method: [Vijay, Arun, Sumit]

Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]

After invoking removeAll() method: [Vijay, Arun, Sumit]

After invoking removeIf() method: [Arun, Sumit]

After invoking clear() method: []

Java HashSet from another Collection

import [Link].*;

class HashSet4{

public static void main(String args[]){

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

HashSet<String> set=new HashSet(list);

[Link]("Gaurav");

Iterator<String> i=[Link]();

while([Link]())

[Link]([Link]());

Vijay

Ravi

Gaurav

Ajay

Java HashSet Example: Book


Let's see a HashSet example where we are adding books to set and printing all the books.

import [Link].*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

public class HashSetExample {

public static void main(String[] args) {

HashSet<Book> set=new HashSet<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to HashSet

[Link](b1);

[Link](b2);

[Link](b3);

//Traversing HashSet

for(Book b:set){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

Output:

101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications & Networking Forouzan Mc Graw Hill 4


103 Operating System Galvin Wiley 6

Java LinkedHashSet class

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

The important points about Java LinkedHashSet class are:

Java LinkedHashSet class contains unique elements only like HashSet.

Java LinkedHashSet class provides all optional set operation and permits null elements.

Java LinkedHashSet class is non synchronized.

Java LinkedHashSet class maintains insertion order.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends HashSet class which implements Set interface. The Set interface inherits
Collection and Iterable interfaces in hierarchical order.

LinkedHashSet class declaration

Let's see the declaration for [Link] class.

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java LinkedHashSet class


Constructor Description

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

HashSet(Collection c) It is used to initialize the hash set by using the elements of the collection c.

LinkedHashSet(int capacity) It is used initialize the capacity of the linked hash set to the given integer value capa

LinkedHashSet(int capacity, float It is used to initialize both the capacity and the fill ratio (also called load capacity)
fillRatio) from its argument.

Java LinkedHashSet Example

Let's see a simple example of Java LinkedHashSet class. Here you can notice that the elements iterate in
insertion order.

import [Link].*;

class LinkedHashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

LinkedHashSet<String> set=new LinkedHashSet();

[Link]("One");

[Link]("Two");

[Link]("Three");

[Link]("Four");

[Link]("Five");

Iterator<String> i=[Link]();

while([Link]())

[Link]([Link]());

One

Two

Three

Four
Five

Java LinkedHashSet example ignoring duplicate Elements

import [Link].*;

class LinkedHashSet2{

public static void main(String args[]){

LinkedHashSet<String> al=new LinkedHashSet<String>();

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Ravi

Vijay

Ajay

Java LinkedHashSet Example: Book

import [Link].*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

}
public class LinkedHashSetExample {

public static void main(String[] args) {

LinkedHashSet<Book> hs=new LinkedHashSet<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to hash table

[Link](b1);

[Link](b2);

[Link](b3);

//Traversing hash table

for(Book b:hs){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

Output:

101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications & Networking Forouzan Mc Graw Hill 4

103 Operating System Galvin Wiley 6

Java TreeSet class


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

The important points about Java TreeSet class are:

Java TreeSet class contains unique elements only like HashSet.

Java TreeSet class access and retrieval times are quiet fast.

Java TreeSet class doesn't allow null element.

Java TreeSet class is non synchronized.

Java TreeSet class maintains ascending order.

Hierarchy of TreeSet class

As shown in the above diagram, Java TreeSet class implements the NavigableSet interface. The NavigableSet
interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order.

TreeSet class declaration

Let's see the declaration for [Link] class.

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable

Constructors of Java TreeSet class

Constructor Description
TreeSet() It is used to construct an empty tree set that will be sorted in ascending order a
natural order of the tree set.

TreeSet(Collection<? extends E> c) It is used to build a new tree set that contains the elements of the collection c.

TreeSet(Comparator<? super E> It is used to construct an empty tree set that will be sorted according to given com
comparator)

TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the elements of the given SortedSet.

Methods of Java TreeSet class

Method Description

boolean add(E e) It is used to add the specified element to this set if it


present.

boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the specified co
set.

E ceiling(E e) It returns the equal or closest greatest element of the sp


from the set, or null there is no such element.

Comparator<? super E> comparator() It returns comparator that arranged elements in order.

Iterator descendingIterator() It is used iterate the elements in descending order.

NavigableSet descendingSet() It returns the elements in reverse order.

E floor(E e) It returns the equal or closest least element of the spe


from the set, or null there is no such element.

SortedSet headSet(E toElement) It returns the group of elements that are less than
element.

NavigableSet headSet(E toElement, boolean inclusive) It returns the group of elements that are less than
inclusive is true) the specified element.

E higher(E e) It returns the closest greatest element of the specified


the set, or null there is no such element.

Iterator iterator() It is used to iterate the elements in ascending order.


E lower(E e) It returns the closest least element of the specified ele
set, or null there is no such element.

E pollFirst() It is used to retrieve and remove the lowest(first) elemen

E pollLast() It is used to retrieve and remove the highest(last) eleme

Spliterator spliterator() It is used to create a late-binding and fail-fast splite


elements.

NavigableSet subSet(E fromElement, boolean fromInclusive, E It returns a set of elements that lie between the given ra
toElement, boolean toInclusive)

SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the give
includes fromElement and excludes toElement.

SortedSet tailSet(E fromElement) It returns a set of elements that are greater than o
specified element.

NavigableSet tailSet(E fromElement, boolean inclusive) It returns a set of elements that are greater than o
inclusive is true) the specified element.

boolean contains(Object o) It returns true if this set contains the specified element.

boolean isEmpty() It returns true if this set contains no elements.

boolean remove(Object o) It is used to remove the specified element from this set i

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

Object clone() It returns a shallow copy of this TreeSet instance.

E first() It returns the first (lowest) element currently in this sorte

E last() It returns the last (highest) element currently in this sort

int size() It returns the number of elements in this set.

Java TreeSet Examples

Java TreeSet Example 1:

Let's see a simple example of Java TreeSet.


import [Link].*;

class TreeSet1{

public static void main(String args[]){

//Creating and adding elements

TreeSet<String> al=new TreeSet<String>();

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ravi");

[Link]("Ajay");

//Traversing elements

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

Test it Now

Output:

Ajay

Ravi

Vijay

Java TreeSet Example 2:

Let's see an example of traversing elements in descending order.

import [Link].*;

class TreeSet2{

public static void main(String args[]){

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

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

[Link]("Traversing element through Iterator in descending order");

Iterator i=[Link]();

while([Link]())
{

[Link]([Link]());

Test it Now

Output:

Traversing element through Iterator in descending order

Vijay

Ravi

Ajay

Traversing element through NavigableSet in descending order

Vijay

Ravi

Ajay

Java TreeSet Example 3:

Let's see an example to retrieve and remove the highest and lowest Value.

import [Link].*;

class TreeSet3{

public static void main(String args[]){

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

[Link](24);

[Link](66);

[Link](12);

[Link](15);

[Link]("Highest Value: "+[Link]());

[Link]("Lowest Value: "+[Link]());

Output:

Highest Value: 12

Lowest Value: 66
Java TreeSet Example 4:

In this example, we perform various NavigableSet operations.

import [Link].*;

class TreeSet4{

public static void main(String args[]){

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

[Link]("A");

[Link]("B");

[Link]("C");

[Link]("D");

[Link]("E");

[Link]("Initial Set: "+set);

[Link]("Reverse Set: "+[Link]());

[Link]("Head Set: "+[Link]("C", true));

[Link]("SubSet: "+[Link]("A", false, "E", true));

[Link]("TailSet: "+[Link]("C", false));

Output:

Initial Set: [A, B, C, D, E]

Reverse Set: [E, D, C, B, A]

Head Set: [A, B, C]

SubSet: [B, C, D, E]

TailSet: [D, E]

Java TreeSet Example 4:

In this example, we perform various SortedSetSet operations.

import [Link].*;

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

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

[Link]("A");

[Link]("B");

[Link]("C");

[Link]("D");

[Link]("E");

[Link]("Intial Set: "+set);

[Link]("Head Set: "+[Link]("C"));

[Link]("SubSet: "+[Link]("A", "E"));

[Link]("TailSet: "+[Link]("C"));

Output:

Intial Set: [A, B, C, D, E]

Head Set: [A, B]

SubSet: [A, B, C, D]

TailSet: [C, D, E]

Java TreeSet Example: Book

Let's see a TreeSet example where we are adding books to set and printing all the books. The elements in
TreeSet must be of a Comparable type. String and Wrapper classes are Comparable by default. To add user-
defined objects in TreeSet, you need to implement the Comparable interface.

import [Link].*;

class Book implements Comparable<Book>{

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;
[Link] = author;

[Link] = publisher;

[Link] = quantity;

public int compareTo(Book b) {

if(id>[Link]){

return 1;

}else if(id<[Link]){

return -1;

}else{

return 0;

public class TreeSetExample {

public static void main(String[] args) {

Set<Book> set=new TreeSet<Book>();

//Creating Books

Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(233,"Operating System","Galvin","Wiley",6);

Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

//Adding Books to TreeSet

[Link](b1);

[Link](b2);

[Link](b3);

//Traversing TreeSet

for(Book b:set){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

Output:

101 Data Communications & Networking Forouzan Mc Graw Hill 4

121 Let us C Yashwant Kanetkar BPB 8


233 Operating System Galvin Wiley 6

Java Queue Interface

Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed
first and last element is removed at last.

Queue Interface declaration

public interface Queue<E> extends Collection<E>

Methods of Java Queue Interface

Method Description

boolean add(object) It is used to insert the specified element into this queue and return true upon success.

boolean offer(object) It is used to insert the specified element into this queue.

Object remove() It is used to retrieves and removes the head of this queue.

Object poll() It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue i

PriorityQueue class

The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO
manner. It inherits AbstractQueue class.

PriorityQueue class declaration

Let's see the declaration for [Link] class.

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Java PriorityQueue Example

import [Link].*;

class TestCollection12{

public static void main(String args[]){

PriorityQueue<String> queue=new PriorityQueue<String>();

[Link]("Amit");

[Link]("Vijay");

[Link]("Karan");

[Link]("Jai");
[Link]("Rahul");

[Link]("head:"+[Link]());

[Link]("head:"+[Link]());

[Link]("iterating the queue elements:");

Iterator itr=[Link]();

while([Link]()){

[Link]([Link]());

[Link]();

[Link]();

[Link]("after removing two elements:");

Iterator<String> itr2=[Link]();

while([Link]()){

[Link]([Link]());

Test it Now

Output:head:Amit

head:Amit

iterating the queue elements:

Amit

Jai

Karan

Vijay

Rahul

after removing two elements:

Karan

Rahul

Vijay

Java PriorityQueue Example: Book

Let's see a PriorityQueue example where we are adding books to queue and printing all the books. The
elements in PriorityQueue must be of Comparable type. String and Wrapper classes are Comparable by
default. To add user-defined objects in PriorityQueue, you need to implement Comparable interface.

import [Link].*;
class Book implements Comparable<Book>{

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

public int compareTo(Book b) {

if(id>[Link]){

return 1;

}else if(id<[Link]){

return -1;

}else{

return 0;

public class LinkedListExample {

public static void main(String[] args) {

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

//Creating Books

Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(233,"Operating System","Galvin","Wiley",6);

Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

//Adding Books to the queue

[Link](b1);

[Link](b2);

[Link](b3);

[Link]("Traversing the queue elements:");

//Traversing queue elements


for(Book b:queue){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

[Link]();

[Link]("After removing one book record:");

for(Book b:queue){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

Output:

Traversing the queue elements:

101 Data Communications & Networking Forouzan Mc Graw Hill 4

233 Operating System Galvin Wiley 6

121 Let us C Yashwant Kanetkar BPB 8

After removing one book record:

121 Let us C Yashwant Kanetkar BPB 8

233 Operating System Galvin Wiley 6

Java Deque Interface

Java Deque Interface is a linear collection that supports element insertion and removal at both ends. Deque is
an acronym for "double ended queue".

Deque Interface declaration

public interface Deque<E> extends Queue<E>

Methods of Java Deque Interface

Method Description

boolean add(object) It is used to insert the specified element into this deque and return true upon success.

boolean offer(object) It is used to insert the specified element into this deque.

Object remove() It is used to retrieves and removes the head of this deque.

Object poll() It is used to retrieves and removes the head of this deque, or returns null if this deque is empty.
Object element() It is used to retrieves, but does not remove, the head of this deque.

Object peek() It is used to retrieves, but does not remove, the head of this deque, or returns null if this deque i

ArrayDeque class

The ArrayDeque class provides the facility of using deque and resizable-array. It inherits AbstractCollection
class and implements the Deque interface.

The important points about ArrayDeque class are:

Unlike Queue, we can add or remove elements from both sides.

Null elements are not allowed in the ArrayDeque.

ArrayDeque is not thread safe, in the absence of external synchronization.

ArrayDeque has no capacity restrictions.

ArrayDeque is faster than LinkedList and Stack.

ArrayDeque Hierarchy

The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page.

ArrayDeque class declaration

Let's see the declaration for [Link] class.

public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializabl


e

Java ArrayDeque Example

import [Link].*;

public class ArrayDequeExample {

public static void main(String[] args) {

//Creating Deque and adding elements

Deque<String> deque = new ArrayDeque<String>();

[Link]("Ravi");

[Link]("Vijay");

[Link]("Ajay");

//Traversing elements

for (String str : deque) {

[Link](str);

}
}

Output:

Ravi

Vijay

Ajay

Java ArrayDeque Example: offerFirst() and pollLast()

import [Link].*;

public class DequeExample {

public static void main(String[] args) {

Deque<String> deque=new ArrayDeque<String>();

[Link]("arvind");

[Link]("vimal");

[Link]("mukul");

[Link]("jai");

[Link]("After offerFirst Traversal...");

for(String s:deque){

[Link](s);

//[Link]();

//[Link]();//it is same as poll()

[Link]();

[Link]("After pollLast() Traversal...");

for(String s:deque){

[Link](s);

Output:

After offerFirst Traversal...

jai

arvind

vimal

mukul
After pollLast() Traversal...

jai

arvind

vimal

Java ArrayDeque Example: Book

import [Link].*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

public class ArrayDequeExample {

public static void main(String[] args) {

Deque<Book> set=new ArrayDeque<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to Deque

[Link](b1);

[Link](b2);

[Link](b3);

//Traversing ArrayDeque

for(Book b:set){

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);

}
}

Output:

101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications & Networking Forouzan Mc Graw Hill 4

103 Operating System Galvin Wiley 6

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an
entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow
null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

Class Description

HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains ascending order.

Useful methods of Map interface


Method Description

V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the map.

V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only if
specified.

V remove(Object key) It is used to delete an entry for the specified key.

boolean remove(Object key, Object value) It removes the specified values with the associated specified keys fro

Set keySet() It returns the Set view containing all the keys.

Set<[Link]<K,V>> entrySet() It returns the Set view containing all the keys and values.

void clear() It is used to reset the map.

V compute(K key, BiFunction<? super K,? super It is used to compute a mapping for the specified key and its current
V,? extends V> remappingFunction) (or null if there is no current mapping).

V computeIfAbsent(K key, Function<? super K,? It is used to compute its value using the given mapping function, if th
extends V> mappingFunction) is not already associated with a value (or is mapped to null), and en
map unless null.

V computeIfPresent(K key, BiFunction<? super K,? It is used to compute a new mapping given the key and its current m
super V,? extends V> remappingFunction) the value for the specified key is present and non-null.

boolean containsValue(Object value) This method returns true if some value equal to the value exists withi
return false.

boolean containsKey(Object key) This method returns true if some key equal to the key exists within
return false.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void forEach(BiConsumer<? super K,? super V> It performs the given action for each entry in the map until all ent
action) processed or the action throws an exception.

V get(Object key) This method returns the object that contains the value associated wit

V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultV
contains no mapping for the key.

int hashCode() It returns the hash code value for the Map

boolean isEmpty() This method returns true if the map is empty; returns false if it conta
key.

V merge(K key, V value, BiFunction<? super V,? If the specified key is not already associated with a value or is assoc
super V,? extends V> remappingFunction) associates it with the given non-null value.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.

void replaceAll(BiFunction<? super K,? super V,? It replaces each entry's value with the result of invoking the given f
extends V> function) entry until all entries have been processed or the function throws an e

Collection values() It returns a collection view of the values contained in the map.

int size() This method returns the number of entries in the map.

[Link] Interface

Entry is the subinterface of Map. So we will be accessed it by [Link] name. It returns a collection-view of
the map, whose elements are of this class. It provides methods to get key and value.

Methods of [Link] interface

Method Description

K getKey() It is used to obtain a key.

V getValue() It is used to obtain value.

int hashCode() It is used to obtain hashCode.

V setValue(V value) It is used to replace the value correspondin


with the specified value.

boolean equals(Object o) It is used to compare the specified object


existing objects.

static <K extends Comparable<? super K>,V> It returns a comparator that compare the ob
Comparator<[Link]<K,V>> comparingByKey() order on key.
static <K,V> Comparator<[Link]<K,V>> It returns a comparator that compare the
comparingByKey(Comparator<? super K> cmp) using the given Comparator.

static <K,V extends Comparable<? super V>> It returns a comparator that compare the ob
Comparator<[Link]<K,V>> comparingByValue() order on value.

static <K,V> Comparator<[Link]<K,V>> It returns a comparator that compare the ob


comparingByValue(Comparator<? super V> cmp) using the given Comparator.

Java Map Example: Non-Generic (Old Style)

//Non-generic

import [Link].*;

public class MapExample1 {

public static void main(String[] args) {

Map map=new HashMap();

//Adding elements to map

[Link](1,"Amit");

[Link](5,"Rahul");

[Link](2,"Jai");

[Link](6,"Amit");

//Traversing Map

Set set=[Link]();//Converting to Set so that we can traverse

Iterator itr=[Link]();

while([Link]()){

//Converting to [Link] so that we can get key and value separately

[Link] entry=([Link])[Link]();

[Link]([Link]()+" "+[Link]());

Output:

1 Amit

2 Jai

5 Rahul

6 Amit

Java Map Example: Generic (New Style)


import [Link].*;

class MapExample2{

public static void main(String args[]){

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

[Link](100,"Amit");

[Link](101,"Vijay");

[Link](102,"Rahul");

//Elements can traverse in any order

for([Link] m:[Link]()){

[Link]([Link]()+" "+[Link]());

Output:

102 Rahul

100 Amit

101 Vijay

Java Map Example: comparingByKey()

import [Link].*;

class MapExample3{

public static void main(String args[]){

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

[Link](100,"Amit");

[Link](101,"Vijay");

[Link](102,"Rahul");

//Returns a Set view of the mappings contained in this map

[Link]()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted([Link]())

//Performs an action for each element of this stream

.forEach([Link]::println);

}
}

Output:

100=Amit

101=Vijay

102=Rahul

Java Map Example: comparingByKey() in Descending Order

import [Link].*;

class MapExample4{

public static void main(String args[]){

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

[Link](100,"Amit");

[Link](101,"Vijay");

[Link](102,"Rahul");

//Returns a Set view of the mappings contained in this map

[Link]()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted([Link]([Link]()))

//Performs an action for each element of this stream

.forEach([Link]::println);

Output:

102=Rahul

101=Vijay

100=Amit

Java Map Example: comparingByValue()

import [Link].*;

class MapExample5{

public static void main(String args[]){

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

[Link](100,"Amit");

[Link](101,"Vijay");
[Link](102,"Rahul");

//Returns a Set view of the mappings contained in this map

[Link]()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted([Link]())

//Performs an action for each element of this stream

.forEach([Link]::println);

Output:

100=Amit

102=Rahul

101=Vijay

Java Map Example: comparingByValue() in Descending Order

import [Link].*;

class MapExample6{

public static void main(String args[]){

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

[Link](100,"Amit");

[Link](101,"Vijay");

[Link](102,"Rahul");

//Returns a Set view of the mappings contained in this map

[Link]()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted([Link]([Link]()))

//Performs an action for each element of this stream

.forEach([Link]::println);

Output:
101=Vijay

102=Rahul

100=Amit

Java HashMap

Java HashMap class implements the Map interface which allows us to store key and value pair, where keys
should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It
is easy to perform operations using the key index like updation, deletion, etc. HashMap class is found in
the [Link] package.

HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null
elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K,V>, where K
stands for key and V for value. It inherits the AbstractMap class and implements the Map interface.

Points to remember

Java HashMap contains values based on the key.

Java HashMap contains only unique keys.

Java HashMap may have one null key and multiple null values.

Java HashMap is non synchronized.

Java HashMap maintains no order.

The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Hierarchy of HashMap class

As shown in the above figure, HashMap class extends AbstractMap class and implements Map interface.

HashMap class declaration

Let's see the declaration for [Link] class.

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

HashMap class Parameters

Let's see the Parameters for [Link] class.

K: It is the type of keys maintained by this map.

V: It is the type of mapped values.

Constructors of Java HashMap class


Constructor Description

HashMap() It is used to construct a default HashMap.

HashMap(Map<? extends K,? extends V> It is used to initialize the hash map by using the elements of the given Map o
m)

HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer valu

HashMap(int capacity, float loadFactor) It is used to initialize both the capacity and load factor of the hash ma
arguments.

Methods of Java HashMap class

Method Description

void clear() It is used to remove all of the mappings from this map.

boolean isEmpty() It is used to return true if this map contains no key-value mappings.

Object clone() It is used to return a shallow copy of this HashMap instance: the k
themselves are not cloned.

Set entrySet() It is used to return a collection view of the mappings contained in this

Set keySet() It is used to return a set view of the keys contained in this map.

V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the map.

V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only if
specified.

V remove(Object key) It is used to delete an entry for the specified key.

boolean remove(Object key, Object value) It removes the specified values with the associated specified keys fro

V compute(K key, BiFunction<? super K,? super It is used to compute a mapping for the specified key and its current
V,? extends V> remappingFunction) (or null if there is no current mapping).

V computeIfAbsent(K key, Function<? super K,? It is used to compute its value using the given mapping function, if th
extends V> mappingFunction) is not already associated with a value (or is mapped to null), and en
map unless null.

V computeIfPresent(K key, BiFunction<? super K,? It is used to compute a new mapping given the key and its current m
super V,? extends V> remappingFunction) the value for the specified key is present and non-null.

boolean containsValue(Object value) This method returns true if some value equal to the value exists withi
return false.

boolean containsKey(Object key) This method returns true if some key equal to the key exists within
return false.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void forEach(BiConsumer<? super K,? super V> It performs the given action for each entry in the map until all ent
action) processed or the action throws an exception.

V get(Object key) This method returns the object that contains the value associated wit

V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultV
contains no mapping for the key.

boolean isEmpty() This method returns true if the map is empty; returns false if it conta
key.

V merge(K key, V value, BiFunction<? super V,? If the specified key is not already associated with a value or is assoc
super V,? extends V> remappingFunction) associates it with the given non-null value.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.

void replaceAll(BiFunction<? super K,? super V,? It replaces each entry's value with the result of invoking the given f
extends V> function) entry until all entries have been processed or the function throws an e

Collection<V> values() It returns a collection view of the values contained in the map.

int size() This method returns the number of entries in the map.

Java HashMap Example

Let's see a simple example of HashMap to store key and value pair.

import [Link].*;

public class HashMapExample1{

public static void main(String args[]){


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

[Link](1,"Mango"); //Put elements in Map

[Link](2,"Apple");

[Link](3,"Banana");

[Link](4,"Grapes");

[Link]("Iterating Hashmap...");

for([Link] m : [Link]()){

[Link]([Link]()+" "+[Link]());

Test it Now

Iterating Hashmap...

1 Mango

2 Apple

3 Banana

4 Grapes

In this example, we are storing Integer as the key and String as the value, so we are
using HashMap<Integer,String> as the type. The put() method inserts the elements in the map.

To get the key and value elements, we should call the getKey() and getValue() methods.
The [Link] interface contains the getKey() and getValue() methods. But, we should call the entrySet()
method of Map interface to get the instance of [Link].

No Duplicate Key on HashMap

You cannot store duplicate keys in HashMap. However, if you try to store duplicate key with another value, it
will replace the value.

import [Link].*;

public class HashMapExample2{

public static void main(String args[]){

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

[Link](1,"Mango"); //Put elements in Map

[Link](2,"Apple");

[Link](3,"Banana");

[Link](1,"Grapes"); //trying duplicate key

[Link]("Iterating Hashmap...");
for([Link] m : [Link]()){

[Link]([Link]()+" "+[Link]());

Test it Now

Iterating Hashmap...

1 Grapes

2 Apple

3 Banana

Java HashMap example to add() elements

Here, we see different ways to insert elements.

import [Link].*;

class HashMap1{

public static void main(String args[]){

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

[Link]("Initial list of elements: "+hm);

[Link](100,"Amit");

[Link](101,"Vijay");

[Link](102,"Rahul");

[Link]("After invoking put() method ");

for([Link] m:[Link]()){

[Link]([Link]()+" "+[Link]());

[Link](103, "Gaurav");

[Link]("After invoking putIfAbsent() method ");

for([Link] m:[Link]()){

[Link]([Link]()+" "+[Link]());

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

[Link](104,"Ravi");

[Link](hm);
[Link]("After invoking putAll() method ");

for([Link] m:[Link]()){

[Link]([Link]()+" "+[Link]());

Initial list of elements: {}

After invoking put() method

100 Amit

101 Vijay

102 Rahul

After invoking putIfAbsent() method

100 Amit

101 Vijay

102 Rahul

103 Gaurav

After invoking putAll() method

100 Amit

101 Vijay

102 Rahul

103 Gaurav

104 Ravi

Java HashMap example to remove() elements

Here, we see different ways to remove elements.

import [Link].*;

public class HashMap2 {

public static void main(String args[]) {

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

[Link](100,"Amit");

[Link](101,"Vijay");

[Link](102,"Rahul");

[Link](103, "Gaurav");

[Link]("Initial list of elements: "+map);


//key-based removal

[Link](100);

[Link]("Updated list of elements: "+map);

//value-based removal

[Link](101);

[Link]("Updated list of elements: "+map);

//key-value pair based removal

[Link](102, "Rahul");

[Link]("Updated list of elements: "+map);

Output:

Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav}

Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav}

Updated list of elements: {102=Rahul, 103=Gaurav}

Updated list of elements: {103=Gaurav}

Java HashMap example to replace() elements

Here, we see different ways to replace elements.

import [Link].*;

class HashMap3{

public static void main(String args[]){

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

[Link](100,"Amit");

[Link](101,"Vijay");

[Link](102,"Rahul");

[Link]("Initial list of elements:");

for([Link] m:[Link]())

[Link]([Link]()+" "+[Link]());

[Link]("Updated list of elements:");

[Link](102, "Gaurav");

for([Link] m:[Link]())
{

[Link]([Link]()+" "+[Link]());

[Link]("Updated list of elements:");

[Link](101, "Vijay", "Ravi");

for([Link] m:[Link]())

[Link]([Link]()+" "+[Link]());

[Link]("Updated list of elements:");

[Link]((k,v) -> "Ajay");

for([Link] m:[Link]())

[Link]([Link]()+" "+[Link]());

Initial list of elements:

100 Amit

101 Vijay

102 Rahul

Updated list of elements:

100 Amit

101 Vijay

102 Gaurav

Updated list of elements:

100 Amit

101 Ravi

102 Gaurav

Updated list of elements:

100 Ajay

101 Ajay

102 Ajay

Difference between HashSet and HashMap


HashSet contains only values whereas HashMap contains an entry(key and value).

Java HashMap Example: Book

import [Link].*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

[Link] = id;

[Link] = name;

[Link] = author;

[Link] = publisher;

[Link] = quantity;

public class MapExample {

public static void main(String[] args) {

//Creating map of Books

Map<Integer,Book> map=new HashMap<Integer,Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to map

[Link](1,b1);

[Link](2,b2);

[Link](3,b3);

//Traversing map

for([Link]<Integer, Book> entry:[Link]()){

int key=[Link]();

Book b=[Link]();

[Link](key+" Details:");

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);


}

Test it Now

Output:

1 Details:

101 Let us C Yashwant Kanetkar BPB 8

2 Details:

102 Data Communications and Networking Forouzan Mc Graw Hill 4

3 Details:

103 Operating System Galvin Wiley 6

You might also like