Java Vector Class Overview and Methods
Java Vector Class Overview and Methods
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.
Vector is synchronized.
Java Vector contains many legacy methods that are not the part of a collections framework.
extends Object<E>
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.
)
Output:
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
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.
It is optional.
What is Collection framework - The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
Algorithm
Do You Know?
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 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?
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.
Iterator<T> iterator()
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.
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{
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
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.
import [Link].*;
[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].*;
[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{
[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.
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.
import [Link].*;
[Link]("Amit Sharma");
[Link]("Vijay Raj");
[Link]("JaiShankar");
[Link]("Raj");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
[Link]();
[Link]();
Iterator<String> itr2=[Link]();
while([Link]()){
[Link]([Link]());
Output:
head:Amit Sharma
head:Amit Sharma
Amit Sharma
Raj
JaiShankar
Vijay Raj
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.
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.
import [Link].*;
[Link]("Gautam");
[Link]("Karan");
[Link]("Ajay");
//Traversing elements
[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.
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].*;
[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.
import [Link].*;
[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.
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.
import [Link].*;
[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.
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.
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.
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.
E get(int index) It is used to fetch the element from the particular position of the list.
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
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.
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 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.
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.
import [Link].*;
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
[Link](list);
Test it Now
Output:
Let's see an example to traverse ArrayList elements using the Iterator interface.
import [Link].*;
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
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].*;
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
for(String fruit:list)
[Link](fruit);
Output:
Test it Now
Mango
Apple
Banana
Grapes
The get() method returns the element at the specified index, whereas the set() method changes the element.
import [Link].*;
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
[Link](1,"Dates");
//Traversing list
for(String fruit:al)
[Link](fruit);
Test it Now
Output:
Mango
Dates
Banana
Grapes
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{
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
[Link](list1);
for(String fruit:list1)
[Link](fruit);
[Link]("Sorting numbers...");
[Link](21);
[Link](11);
[Link](51);
[Link](1);
[Link](list2);
for(Integer number:list2)
[Link](number);
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
11
21
51
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{
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
ListIterator<String> list1=[Link]([Link]());
while([Link]())
String str=[Link]();
[Link](str);
for(int i=0;i<[Link]();i++)
[Link]([Link](i));
[Link](a);
});
Iterator<String> itr=[Link]();
[Link](a);
});
Output:
Ajay
Ravi
Vijay
Ravi
Ravi
Vijay
Ravi
Ajay
Ravi
Vijay
Ravi
Ajay
Ravi
Vijay
Ravi
Ajay
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{
//creating arraylist
[Link](s2);
[Link](s3);
//Getting Iterator
Iterator itr=[Link]();
while([Link]()){
Student st=(Student)[Link]();
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
import [Link].*;
import [Link].*;
class ArrayList6 {
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
try
//Serialization
[Link](al);
[Link]();
[Link]();
//Deserialization
ArrayList list=(ArrayList)[Link]();
[Link](list);
}catch(Exception e)
[Link](e);
Output:
import [Link].*;
class ArrayList7{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link](1, "Gaurav");
[Link]("Sonoo");
[Link]("Hanumat");
[Link](al2);
[Link]("John");
[Link]("Rahul");
[Link](1, al3);
Output:
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
import [Link].*;
class ArrayList8 {
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Anuj");
[Link]("Gaurav");
[Link]("Vijay");
[Link](0);
[Link]("Ravi");
[Link]("Hanumat");
[Link](al2);
[Link]();
Output:
import [Link].*;
class ArrayList9{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Ravi");
[Link]("Hanumat");
[Link](al2);
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
Output:
Ravi
import [Link].*;
class ArrayList10{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("After Insertion");
Output:
After Insertion
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;
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
//Traversing list
for(Book b:list){
Test it Now
Output:
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and implements List
and Deque interfaces.
In the case of a doubly linked list, we can add or remove elements from both sides.
Constructor Description
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.
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.
Iterator<E> descendingIterator() It is used to return an iterator over the elements in a deque in reverse sequential
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.
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.
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 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 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.
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.
import [Link].*;
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
Output: Ravi
Vijay
Ravi
Ajay
import [Link].*;
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link](1, "Gaurav");
[Link]("Sonoo");
[Link]("Hanumat");
[Link](ll2);
[Link]("John");
[Link]("Rahul");
[Link](1, ll3);
[Link]("Lokesh");
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
import [Link].*;
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Anuj");
[Link]("Gaurav");
[Link]("Harsh");
[Link]("Virat");
[Link]("Gaurav");
[Link]("Harsh");
[Link]("Amit");
[Link]("Vijay");
[Link](0);
[Link]("Ravi");
[Link]("Hanumat");
[Link](ll2);
[Link](ll2);
[Link]();
[Link]();
[Link]("Gaurav");
[Link]("Harsh");
[Link]();
}
}
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]
import [Link].*;
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
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;
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
//Traversing list
for(Book b:list){
Output:
101 Let us C Yashwant Kanetkar BPB 8
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.
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.
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.
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.
The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to
create the List:
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.
Let's see a simple example of List where we are using the ArrayList class as the implementation.
import [Link].*;
//Creating a List
List<String> list=new ArrayList<String>();
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
for(String fruit:list)
[Link](fruit);
Test it Now
Output:
Mango
Apple
Banana
Grapes
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].*;
//Creating Array
String[] array={"Java","Python","PHP","C++"};
for(String lang:array){
[Link](lang);
Test it Now
Output:
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].*;
[Link]("Mango");
[Link]("Banana");
[Link]("Apple");
[Link]("Strawberry");
Test it Now
Output:
The get() method returns the element at the given index, whereas the set() method changes or replaces the
element.
import [Link].*;
//Creating a List
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
[Link]("Returning element: "+[Link](1));//it will return the 2nd element, because index starts fro
m0
[Link](1,"Dates");
for(String fruit:list)
[Link](fruit);
Test it Now
Output:
Mango
Dates
Banana
Grapes
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{
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
[Link](list1);
for(String fruit:list1)
[Link](fruit);
[Link]("Sorting numbers...");
[Link](21);
[Link](11);
[Link](51);
[Link](1);
[Link](list2);
for(Integer number:list2)
[Link](number);
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
11
21
51
ListIterator Interface is used to traverse the element in a backward and forward direction.
ListIterator Interface declaration
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
import [Link].*;
[Link]("Amit");
[Link]("Vijay");
[Link]("Kumar");
[Link](1,"Sachin");
ListIterator<String> itr=[Link]();
while([Link]()){
[Link]("index:"+[Link]()+" value:"+[Link]());
}
while([Link]()){
[Link]("index:"+[Link]()+" value:"+[Link]());
Output:
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit
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;
}
}
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
//Traversing list
for(Book b:list){
Test it Now
Output:
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.
HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
The initial default capacity of HashSet is 16, and the load factor is 0.75.
A list can contain duplicate elements whereas Set contains unique elements only.
The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits
Collection and Iterable interfaces in hierarchical order.
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)
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)
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)
9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
import [Link].*;
class HashSet1{
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
Iterator<String> i=[Link]();
while([Link]())
[Link]([Link]());
Five
One
Four
Two
Three
import [Link].*;
class HashSet2{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
Ajay
Vijay
Ravi
import [Link].*;
class HashSet3{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Arun");
[Link]("Sumit");
[Link]("Ravi");
[Link]("Ajay");
[Link]("Gaurav");
[Link](set1);
[Link](set1);
[Link](str->[Link]("Vijay"));
[Link]();
import [Link].*;
class HashSet4{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Gaurav");
Iterator<String> i=[Link]();
while([Link]())
[Link]([Link]());
Vijay
Ravi
Gaurav
Ajay
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;
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
//Traversing HashSet
for(Book b:set){
Output:
Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. It inherits HashSet
class and implements Set interface.
Java LinkedHashSet class provides all optional set operation and permits null elements.
The LinkedHashSet class extends HashSet class which implements Set interface. The Set interface inherits
Collection and Iterable interfaces in hierarchical order.
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.
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{
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
Iterator<String> i=[Link]();
while([Link]())
[Link]([Link]());
One
Two
Three
Four
Five
import [Link].*;
class LinkedHashSet2{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
Ravi
Vijay
Ajay
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 {
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
for(Book b:hs){
Output:
Java TreeSet class access and retrieval times are quiet fast.
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.
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.
Method Description
boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the specified co
set.
Comparator<? super E> comparator() It returns comparator that arranged elements in order.
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.
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 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.
class TreeSet1{
[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
import [Link].*;
class TreeSet2{
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
Iterator i=[Link]();
while([Link]())
{
[Link]([Link]());
Test it Now
Output:
Vijay
Ravi
Ajay
Vijay
Ravi
Ajay
Let's see an example to retrieve and remove the highest and lowest Value.
import [Link].*;
class TreeSet3{
[Link](24);
[Link](66);
[Link](12);
[Link](15);
Output:
Highest Value: 12
Lowest Value: 66
Java TreeSet Example 4:
import [Link].*;
class TreeSet4{
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link]("E");
Output:
SubSet: [B, C, D, E]
TailSet: [D, E]
import [Link].*;
class TreeSet4{
public static void main(String args[]){
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link]("E");
[Link]("TailSet: "+[Link]("C"));
Output:
SubSet: [A, B, C, D]
TailSet: [C, D, E]
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].*;
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;
if(id>[Link]){
return 1;
}else if(id<[Link]){
return -1;
}else{
return 0;
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
//Traversing TreeSet
for(Book b:set){
Output:
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.
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.
import [Link].*;
class TestCollection12{
[Link]("Amit");
[Link]("Vijay");
[Link]("Karan");
[Link]("Jai");
[Link]("Rahul");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
[Link]();
[Link]();
Iterator<String> itr2=[Link]();
while([Link]()){
[Link]([Link]());
Test it Now
Output:head:Amit
head:Amit
Amit
Jai
Karan
Vijay
Rahul
Karan
Rahul
Vijay
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;
if(id>[Link]){
return 1;
}else if(id<[Link]){
return -1;
}else{
return 0;
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
[Link]();
for(Book b:queue){
Output:
Java Deque Interface is a linear collection that supports element insertion and removal at both ends. Deque is
an acronym for "double ended queue".
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.
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page.
import [Link].*;
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
//Traversing elements
[Link](str);
}
}
Output:
Ravi
Vijay
Ajay
import [Link].*;
[Link]("arvind");
[Link]("vimal");
[Link]("mukul");
[Link]("jai");
for(String s:deque){
[Link](s);
//[Link]();
[Link]();
for(String s:deque){
[Link](s);
Output:
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal
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;
//Creating Books
[Link](b1);
[Link](b2);
[Link](b3);
//Traversing ArrayDeque
for(Book b:set){
}
}
Output:
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.
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.
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.
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.
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.
Method Description
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.
//Non-generic
import [Link].*;
[Link](1,"Amit");
[Link](5,"Rahul");
[Link](2,"Jai");
[Link](6,"Amit");
//Traversing Map
Iterator itr=[Link]();
while([Link]()){
[Link] entry=([Link])[Link]();
[Link]([Link]()+" "+[Link]());
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
class MapExample2{
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
Output:
102 Rahul
100 Amit
101 Vijay
import [Link].*;
class MapExample3{
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link]()
.stream()
.sorted([Link]())
.forEach([Link]::println);
}
}
Output:
100=Amit
101=Vijay
102=Rahul
import [Link].*;
class MapExample4{
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link]()
.stream()
.sorted([Link]([Link]()))
.forEach([Link]::println);
Output:
102=Rahul
101=Vijay
100=Amit
import [Link].*;
class MapExample5{
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link]()
.stream()
.sorted([Link]())
.forEach([Link]::println);
Output:
100=Amit
102=Rahul
101=Vijay
import [Link].*;
class MapExample6{
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link]()
.stream()
.sorted([Link]([Link]()))
.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 may have one null key and multiple null values.
The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
As shown in the above figure, HashMap class extends AbstractMap class and implements Map interface.
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.
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.
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.
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.
Let's see a simple example of HashMap to store key and value pair.
import [Link].*;
[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].
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].*;
[Link](2,"Apple");
[Link](3,"Banana");
[Link]("Iterating Hashmap...");
for([Link] m : [Link]()){
[Link]([Link]()+" "+[Link]());
Test it Now
Iterating Hashmap...
1 Grapes
2 Apple
3 Banana
import [Link].*;
class HashMap1{
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
[Link](103, "Gaurav");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
[Link](104,"Ravi");
[Link](hm);
[Link]("After invoking putAll() method ");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
100 Amit
101 Vijay
102 Rahul
100 Amit
101 Vijay
102 Rahul
103 Gaurav
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
import [Link].*;
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link](103, "Gaurav");
[Link](100);
//value-based removal
[Link](101);
[Link](102, "Rahul");
Output:
import [Link].*;
class HashMap3{
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
for([Link] m:[Link]())
[Link]([Link]()+" "+[Link]());
[Link](102, "Gaurav");
for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
for([Link] m:[Link]())
[Link]([Link]()+" "+[Link]());
for([Link] m:[Link]())
[Link]([Link]()+" "+[Link]());
100 Amit
101 Vijay
102 Rahul
100 Amit
101 Vijay
102 Gaurav
100 Amit
101 Ravi
102 Gaurav
100 Ajay
101 Ajay
102 Ajay
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;
//Creating Books
[Link](1,b1);
[Link](2,b2);
[Link](3,b3);
//Traversing map
int key=[Link]();
Book b=[Link]();
[Link](key+" Details:");
Test it Now
Output:
1 Details:
2 Details:
3 Details: