0% found this document useful (0 votes)
4 views36 pages

Java Queue and PriorityQueue Overview

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)
4 views36 pages

Java Queue and PriorityQueue Overview

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 Queue Interface

The interface Queue is available in the [Link] package and does extend the
Collection interface. It is used to keep the elements that are processed in the
First In First Out (FIFO) manner. It is an ordered list of objects, where
insertion of elements occurs at the end of the list, and removal of elements
occur at the beginning of the list.

Being an interface, the queue requires, for the declaration, a concrete class,
and the most common classes are the LinkedList and PriorityQueue in Java.
Implementations done by these classes are not thread safe. If it is required
to have a thread safe implementation, PriorityBlockingQueue is an available
option.

Queue Interface Declaration

1. public interface Queue<E> extends Collection<E>

Methods of Java Queue Interface

Method Description

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

boolean It is used to insert the specified element into this queue.


offer(object)

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 i
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 return
if this queue is empty.

Features of a Queue
The following are some important features of a queue.

o As discussed earlier, FIFO concept is used for insertion and deletion of


elements from a queue.
o The Java Queue provides support for all of the methods of the Collection
interface including deletion, insertion, etc.
o PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations
that are used most frequently.
o The NullPointerException is raised, if any null operation is done on the
BlockingQueues.
o Those Queues that are present in the util package are known as Unbounded
Queues.
o Those Queues that are present in the [Link] package are known as
bounded Queues.
o All Queues barring the Deques facilitates removal and insertion at the head
and tail of the queue; respectively. In fact, deques support element insertion
and removal at both ends.

PriorityQueue Class
PriorityQueue is also class that is defined in the collection framework that
gives us a way for processing the objects on the basis of priority. It is already
described that the insertion and deletion of objects follows FIFO pattern in
the Java queue. However, sometimes the elements of the queue are needed
to be processed according to the priority, that's where a PriorityQueue
comes into action.

PriorityQueue Class Declaration


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

1. public class PriorityQueue<E> extends AbstractQueue<E> implements Serializa


ble

Java PriorityQueue Example


FileName: [Link]
1. import [Link].*;
2. class TestCollection12{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. [Link]("Amit");
6. [Link]("Vijay");
7. [Link]("Karan");
8. [Link]("Jai");
9. [Link]("Rahul");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
[Link]("iterating the queue elements:");
[Link] itr=[Link]();
[Link]([Link]()){
[Link]([Link]());
16.}
[Link]();
[Link]();
[Link]("after removing two elements:");
[Link]<String> itr2=[Link]();
[Link]([Link]()){
[Link]([Link]());
23.}
24.}
25.}
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.

FileName: [Link]

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]
y);
}
}
}

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


The interface called Deque is present in [Link] package. It is the subtype of
the interface queue. The Deque supports the addition as well as the removal
of elements from both ends of the data structure. Therefore, a deque can be
used as a stack or a queue. We know that the stack supports the Last In First
Out (LIFO) operation, and the operation First In First Out is supported by a
queue. As a deque supports both, either of the mentioned operations can be
performed on it. Deque is an acronym for "double ended queue".

Deque Interface declaration


1. public interface Deque<E> extends Queue<E>

Methods of Java Deque Interface

Method Description

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

boolean It is used to insert the specified element into this deque.


offer(object)

Object It is used to retrieve and removes the head of this deque.


remove()

Object poll() It is used to retrieve and removes the head of this deque, or returns n
this deque is empty.

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

Object peek() It is used to retrieve, but does not remove, the head of this deque, or ret
null if this deque is empty.

Object The method returns the head element of the deque. The method does
peekFirst() remove any element from the deque. Null is returned by this method, w
the deque is empty.

Object The method returns the last element of the deque. The method does
peekLast() remove any element from the deque. Null is returned by this method, w
the deque is empty.

Boolean Inserts the element e at the front of the queue. If the insertion is succes
offerFirst(e) true is returned; otherwise, false.

Object Inserts the element e at the tail of the queue. If the insertion is succes
offerLast(e) true is returned; otherwise, false.

ArrayDeque class
We know that it is not possible to create an object of an interface in Java.
Therefore, for instantiation, we need a class that implements the Deque
interface, and that class is ArrayDeque. It grows and shrinks as per usage. It
also inherits the AbstractCollection class.

The important points about ArrayDeque class are:

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


o Null elements are not allowed in the ArrayDeque.
o ArrayDeque is not thread safe, in the absence of external
synchronization.
o ArrayDeque has no capacity restrictions.
o 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.

1. public class ArrayDeque<E> extends AbstractCollection<E> implements


Deque<E>, Cloneable, Serializable

Java ArrayDeque Example


FileName: [Link]

1. import [Link].*;
2. public class ArrayDequeExample {
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. [Link](str);
12. }
13. }
14. }

Output:

Ravi
Vijay
Ajay

Java ArrayDeque Example: offerFirst() and pollLast()


FileName: [Link]
1. import [Link].*;
2. public class DequeExample {
3. public static void main(String[] args) {
4. Deque<String> deque=new ArrayDeque<String>();
5. [Link]("arvind");
6. [Link]("vimal");
7. [Link]("mukul");
8. [Link]("jai");
9. [Link]("After offerFirst Traversal...");
10. for(String s:deque){
11. [Link](s);
12. }
13. //[Link]();
14. //[Link]();//it is same as poll()
15. [Link]();
16. [Link]("After pollLast() Traversal...");
17. for(String s:deque){
18. [Link](s);
19. }
20. }
21. }

Output:

After offerFirst Traversal...


jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal

Java ArrayDeque Example: Book


FileName: [Link]

1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity
){
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class ArrayDequeExample {
15. public static void main(String[] args) {
16. Deque<Book> set=new ArrayDeque<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","For
ouzan","Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to Deque
22. [Link](b1);
23. [Link](b2);
24. [Link](b3);
25. //Traversing ArrayDeque
26. for(Book b:set){
27. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+
" "+[Link]);
28. }
29. }
30. }

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

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

Java Vector class Declaration

1. public class Vector<E>


2. extends Object<E>
3. 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


capacity and with its capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the specified


capacityIncrement) capacity and capacity increment.

4) Vector( Collection<? extends It constructs a vector that contains the elements


E> c) collection 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 th


of this Vector.

3) addElement() It is used to append the specified component to the end of this vect
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 spe
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 us


necessary. It ensures that the vector can hold at least the numb
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
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 eleme
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 v
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 sequ

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 eleme
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 p
sequence.

25) remove() It is used to remove the specified element from the vector. If the v
does not contain the element, it is unchanged.

26) removeAll() It is used to delete all the elements from the vector that are present i
specified collection.
27) removeAllElemen It is used to remove all elements from the vector and set the size o
ts() vector to zero.

28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argu
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 satisf
given predicate.

31) removeRange() It is used to delete all of the elements from the vector whose ind
between fromIndex, inclusive and toIndex, exclusive.

32) replaceAll() It is used to replace each element of the list with the result of applyin
operator to that element.

33) retainAll() It is used to retain only that element in the vector which is contained i
specified collection.

34) set() It is used to replace the element at the specified position in the vector
the specified element.

35) setElementAt() It is used to set the component at the specified index of the vector t
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 spe
Comparator.

39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elem
in the list.

40) subList() It is used to get a view of the portion of the list between fromI
inclusive, and toIndex, exclusive.

41) toArray() It is used to get an array containing all of the elements in this vect
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


1. import [Link].*;
2. public class VectorExample {
3. public static void main(String args[]) {
4. //Create a vector
5. Vector<String> vec = new Vector<String>();
6. //Adding elements using add() method of List
7. [Link]("Tiger");
8. [Link]("Lion");
9. [Link]("Dog");
10. [Link]("Elephant");
11. //Adding elements using addElement() method of Vector
12. [Link]("Rat");
13. [Link]("Cat");
14. [Link]("Deer");
15.
16. [Link]("Elements are: "+vec);
17. }
18.}
Test it Now

Output:

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

Java Vector Example 2


1. import [Link].*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. [Link]("Tiger");
8. [Link]("Lion");
9. [Link]("Dog");
10. [Link]("Elephant");
11. //Check size and capacity
12. [Link]("Size is: "+[Link]());
13. [Link]("Default capacity is: "+[Link]());
14. //Display Vector elements
15. [Link]("Vector element is: "+vec);
16. [Link]("Rat");
17. [Link]("Cat");
18. [Link]("Deer");
19. //Again check size and capacity after two insertions
20. [Link]("Size after addition: "+[Link]());
21. [Link]("Capacity after addition is: "+[Link]());
22. //Display Vector elements again
23. [Link]("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if([Link]("Tiger"))
26. {
27. [Link]("Tiger is present at the index " +[Link]("Tiger"));
28. }
29. else
30. {
31. [Link]("Tiger is not present in the list.");
32. }
33. //Get the first element
34. [Link]("The first animal of the vector is = "+[Link]());
35. //Get the last element
36. [Link]("The last animal of the vector is = "+[Link]());
37. }
38.}
Test it Now

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


1. import [Link].*;
2. public class VectorExample2 {
3. public static void main(String args[]) {
4. //Create an empty Vector
5. Vector<Integer> in = new Vector<>();
6. //Add elements in the vector
7. [Link](100);
8. [Link](200);
9. [Link](300);
10. [Link](200);
11. [Link](400);
12. [Link](500);
13. [Link](600);
14. [Link](700);
15. //Display the vector elements
16. [Link]("Values in vector: " +in);
17. //use remove() method to delete the first occurence of an element
18. [Link]("Remove first occourence of element 200: "+[Link]((Int
eger)200));
19. //Display the vector elements afre remove() method
20. [Link]("Values in vector: " +in);
21. //Remove the element at index 4
22. [Link]("Remove element at index 4: " +[Link](4));
23. [Link]("New Value list in vector: " +in);
24. //Remove an element
25. [Link](5);
26. //Checking vector and displays the element
27. [Link]("Vector element after removal: " +in);
28. //Get the hashcode for this vector
29. [Link]("Hash code of this vector = "+[Link]());
30. //Get the element at specified index
31. [Link]("Element at index 1 is = "+[Link](1));
32. }
33.}
Test it Now

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

Java Stack
The stack is a linear data structure that is used to store the collection of
objects. It is based on Last-In-First-Out (LIFO). Java collection framework
provides many interfaces and classes to store the collection of objects. One
of them is the Stack class that provides different operations such as push,
pop, search, etc.

In this section, we will discuss the Java Stack class,


its methods, and implement the stack data structure in a Java program.
But before moving to the Java Stack class have a quick view of how the stack
works.

The stack data structure has the two most important operations that
are push and pop. The push operation inserts an element into the stack and
pop operation removes an element from the top of the stack. Let's see how
they work on stack.

Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

Let's remove (pop) 18, 45, and 11 from the stack.


Empty Stack: If the stack has no element is known as an empty stack.
When the stack is empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the
following figure,

o Push 12, top=0


o Push 6, top=1
o Push 9, top=2
When we pop an element from the stack the value of top is decreased by
1. In the following figure, we have popped 9.
The following table shows the different values of the top.

Java Stack Class


In Java, Stack is a class that falls under the Collection framework that
extends the Vector class. It also implements interfaces List, Collection,
Iterable, Cloneable, Serializable. It represents the LIFO stack of objects.
Before using the Stack class, we must import the [Link] package. The stack
class arranged in the Collections framework hierarchy, as shown below.
Stack Class Constructor
The Stack class contains only the default constructor that creates an
empty stack.

1. public Stack()

Creating a Stack
If we want to create a stack, first, import the [Link] package and create an
object of the Stack class.

1. Stack stk = new Stack();

Or
1. Stack<type> stk = new Stack<>();

Where type denotes the type of stack like Integer, String, etc.

Methods of the Stack Class


We can perform push, pop, peek and search operation on the stack. The Java
Stack class provides mainly five methods to perform these operations. Along
with this, it also provides all the methods of the Java Vector class.

Method Modifier and Method Description


Type

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

push(E item) E The method pushes (insert) an element onto the top of the stac

pop() E The method removes an element from the top of the stack
returns the same element as the value of that function.

peek() E The method looks at the top element of the stack without rem
it.

search(Objec int The method searches the specified object and returns the posit
t o) the object.

Stack Class empty() Method


The empty() method of the Stack class check the stack is empty or not. If
the stack is empty, it returns true, else returns false. We can also use
the isEmpty() method of the Vector class.

Syntax

1. public boolean empty()

Returns: The method returns true if the stack is empty, else returns false.

In the following example, we have created an instance of the Stack class.


After that, we have invoked the empty() method two times. The first time it
returns true because we have not pushed any element into the stack. After
that, we have pushed elements into the stack. Again we have invoked the
empty() method that returns false because the stack is not empty.

[Link]

1. import [Link];
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = [Link]();
[Link]("Is the stack empty? " + result);
11.// pushing elements into stack
[Link](78);
[Link](113);
[Link](90);
[Link](120);
16.//prints elements of the stack
[Link]("Elements in Stack: " + stk);
[Link] = [Link]();
[Link]("Is the stack empty? " + result);
20.}
21.}

Output:

Is the stack empty? true


Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false

Stack Class push() Method


The method inserts an item onto the top of the stack. It works the same as
the method addElement(item) method of the Vector class. It passes a
parameter item to be pushed into the stack.
Syntax

1. public E push(E item)

Parameter: An item to be pushed onto the top of the stack.

Returns: The method returns the argument that we have passed as a


parameter.

Stack Class pop() Method


The method removes an object at the top of the stack and returns the same
object. It throws EmptyStackException if the stack is empty.

Syntax

1. public E pop()

Returns: It returns an object that is at the top of the stack.

Let's implement the stack in a Java program and perform push and pop
operations.

[Link]

1. import [Link].*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. [Link]("stack: " + stk);
9. //pushing elements into the stack
[Link](stk, 20);
[Link](stk, 13);
[Link](stk, 89);
[Link](stk, 90);
[Link](stk, 11);
[Link](stk, 45);
[Link](stk, 18);
17.//popping elements from the stack
[Link](stk);
[Link](stk);
20.//throws exception if the stack is empty
[Link]
22.{
[Link](stk);
24.}
[Link] (EmptyStackException e)
26.{
[Link]("empty stack");
28.}
29.}
30.//performing push operation
[Link] void pushelmnt(Stack stk, int x)
32.{
33.//invoking push() method
[Link](new Integer(x));
[Link]("push -> " + x);
36.//prints modified stack
[Link]("stack: " + stk);
38.}
39.//performing pop operation
[Link] void popelmnt(Stack stk)
41.{
[Link]("pop -> ");
43.//invoking pop() method
[Link] x = (Integer) [Link]();
[Link](x);
46.//prints modified stack
[Link]("stack: " + stk);
48.}
49.}
Output:

stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]

Stack Class peek() Method


It looks at the element that is at the top in the stack. It also
throws EmptyStackException if the stack is empty.

Syntax

1. public E peek()

Returns: It returns the top elements of the stack.

Let's see an example of the peek() method.

[Link]

1. import [Link];
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. [Link]("Apple");
9. [Link]("Grapes");
[Link]("Mango");
[Link]("Orange");
[Link]("Stack: " + stk);
13.// Access element from the top of the stack
[Link] fruits = [Link]();
15.//prints stack
[Link]("Element at top: " + fruits);
17.}
18.}

Output:

Stack: [Apple, Grapes, Mango, Orange]


Element at the top of the stack: Orange

Stack Class search() Method


The method searches the object in the stack from the top. It parses a
parameter that we want to search for. It returns the 1-based location of the
object in the stack. Thes topmost object of the stack is considered at
distance 1.

Suppose, o is an object in the stack that we want to search for. The method
returns the distance from the top of the stack of the occurrence nearest the
top of the stack. It uses equals() method to search an object in the stack.

Syntax

1. public int search(Object o)

Parameter: o is the desired object to be searched.

Returns: It returns the object location from the top of the stack. If it returns
-1, it means that the object is not on the stack.

Let's see an example of the search() method.

[Link]
import [Link];
public class StackSearchMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
[Link]("Mac Book");
[Link]("HP");
[Link]("DELL");
[Link]("Asus");
[Link]("Stack: " + stk);
// Search an element
int location = [Link]("HP");
[Link]("Location of Dell: " + location);
}
}

Java Stack Operations


Size of the Stack
We can also find the size of the stack using the size() method of the Vector
class. It returns the total number of elements (size of the stack) in the stack.

Syntax

1. public int size()

Let's see an example of the size() method of the Vector class.

[Link]

1. import [Link];
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. [Link](22);
8. [Link](33);
9. [Link](44);
[Link](55);
[Link](66);
12.// Checks the Stack is empty or not
[Link] rslt=[Link]();
[Link]("Is the stack empty or not? " +rslt);
15.// Find the size of the Stack
[Link] x=[Link]();
[Link]("The stack size is: "+x);
18.}
19.}

Output:

Is the stack empty or not? false


The stack size is: 5

Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of
the stack using three different methods are as follows:

o Using iterator() Method


o Using forEach() Method
o Using listIterator() Method

Using the iterator() Method

It is the method of the Iterator interface. It returns an iterator over the


elements in the stack. Before using the iterator() method import
the [Link] package.

Syntax

1. Iterator<T> iterator()
Let's perform an iteration over the stack.

[Link]

1. import [Link];
2. import [Link];
3. public class StackIterationExample1
4. {
5. public static void main (String[] args)
6. {
7. //creating an object of Stack class
8. Stack stk = new Stack();
9. //pushing elements into stack
[Link]("BMW");
[Link]("Audi");
[Link]("Ferrari");
[Link]("Bugatti");
[Link]("Jaguar");
15.//iteration over the stack
[Link] iterator = [Link]();
[Link]([Link]())
18.{
[Link] values = [Link]();
[Link](values);
21.}
22.}
23.}

Output:

BMW
Audi
Ferrari
Bugatti
Jaguar

Using the forEach() Method


Java provides a forEach() method to iterate over the elements. The method is
defined in the Iterable and Stream interface.

Syntax

1. default void forEach(Consumer<super T>action)

Let's iterate over the stack using the forEach() method.

[Link]

1. import [Link].*;
2. public class StackIterationExample2
3. {
4. public static void main (String[] args)
5. {
6. //creating an instance of Stack class
7. Stack <Integer> stk = new Stack<>();
8. //pushing elements into stack
9. [Link](119);
[Link](203);
[Link](988);
[Link]("Iteration over the stack using forEach() Method:");
13.//invoking forEach() method for iteration over the stack
[Link](n ->
15.{
[Link](n);
17.});
18.}
19.}

Output:

Iteration over the stack using forEach() Method:


119
203
988

Using listIterator() Method


This method returns a list iterator over the elements in the mentioned list (in
sequence), starting at the specified position in the list. It iterates the stack
from top to bottom.

Syntax

1. ListIterator listIterator(int index)

Parameter: The method parses a parameter named index.

Returns: This method returns a list iterator over the elements, in sequence.

Exception: It throws IndexOutOfBoundsException if the index is out of


range.

Let's iterate over the stack using the listIterator() method.

[Link]

1. import [Link];
2. import [Link];
3. import [Link];
4.
5. public class StackIterationExample3
6. {
7. public static void main (String[] args)
8. {
9. Stack <Integer> stk = new Stack<>();
[Link](119);
[Link](203);
[Link](988);
[Link]<Integer> ListIterator = [Link]([Link]());
[Link]("Iteration over the Stack from top to bottom:");
[Link] ([Link]())
16.{
[Link] avg = [Link]();
[Link](avg);
19.}
20.}
21.}

Output:

Iteration over the Stack from top to bottom:


988
203
119

You might also like