Count All Stack Elements in Java



In this tutorial, we will learn to count the number of elements in the stack using various approaches. In Java, a Stack is a fundamental data structure that follows the Last-In-First-Out (LIFO) principle, meaning whatever element is recently added to the stack, will be accessed first.

The real-time applications of the stack are function call management, expression evaluation, etc. In such scenarios, we might need to count the number of stack elements. For example, counting the total number of function calls while using the stack for function call management and the total number of operations to be performed while evaluating the mathematical expression using the stack.

Here, we will explore below three approaches to counting a number of elements in the stack.

  • Using a Stack.size() Method
  • Using the For Loop (Iterative Approach)
  • Using the Recursive Approach

Using a Stack.size() Method

The first approach to count the number of elements in the stack is using the Stack.size() method. It helps in finding the size of the stack, which is equivalent to the total number of elements in the stack.

Syntax

Users can follow the syntax below to use the sack.size() method in Java.

s1.size();

In the above syntax, 's1' is a stack data structure containing number, string, boolean, etc. elements.


Parameters

The Stack.size() method doesn't take any parameter.


Return Value

The Stack.size() method returns the total number of elements in the stack.


Example

In the code below, we have defined the 's1' stack. After that, we inserted 3 integers in the stack. When we use the size() method with the stack, it returns '3' as an output, representing the total number of elements in the stack.

import java.util.Stack;

public class StackExample {
public static void main(String[] args) {
Stack s1 = new Stack<>();

// Insert elements onto the stack
s1.push(1);
s1.push(2);
s1.push(3);

// Get number of elements using size() method
int count = s1.size();

// Print the count of elements
System.out.println("Number of elements in the stack: " + count);
}
}


Output


Number of elements in the stack: 3


Using the For Loop (Iterative Approach)

Now, let's look at the second approach for counting the number of elements in the stack. In this approach, we will use the 'for' loop to traverse through each element of the stack and count the total number of elements in the stack.


Syntax

Users can follow the syntax below to count the total number of elements in the stack using the 'for' loop.

for (Integer element : s1) {
count++;
}

In the above syntax, 's1' is a stack, and we are iterating through the elements of the 's1' stack. In the loop body, we increment the 'count' variable value by 1, which stores the number of elements in the stack.


Example

In the example below, we use the 'for' loop to traverse through each element of the stack and increment the value of the 'count' variable in each iteration. After that, we print the value of the 'count' variable, which is the number of elements in the stack.

import java.util.Stack;

public class StackCountIterative {
public static void main(String[] args) {
Stack s1 = new Stack<>();

// Insert elements onto the stack
s1.push(1);
s1.push(2);
s1.push(3);

// Count elements using iteration
int count = 0;
for (Integer element : s1) {
count++;
}

// Print the count of elements
System.out.println("Number of elements in the stack: " + count);
}
}

Output

Number of elements in the stack: 3


Using the Recursive Approach

The third approach to count all stack elements is using the recursion. In this approach, we will traverse each element of the stack recursively and keep track of the total number of elements in the stack.

Syntax

Users can follow the syntax below to use the recursive approach to count all stack elements.

if (s1.isEmpty()) {
return 0;
}
// Remove the top element and count the rest
Integer element = s1.pop();
int count = 1 + countElements(s1);
// Push the element back to restore the stack
s1.push(element);

In the above syntax, we follow below steps:


  1. If the stack is empty, return '0', representing there are no elements in the stack.
  2. Remove the elements from the stack as we will count the occurrence of the current element in the next step.
  3. Make a recursive call with the updated stack add its resultant value to the '1' and store it in the 'count' variable. Here, we add '1' for the previously removed element.
  4. Next, push the 'element' again in the stack to keep the stack state the same.


Example

In this example, we have used the recursive approach to calculate the number of elements in the stack.

import java.util.Stack;

public class StackCountRecursive {
public static void main(String[] args) {
Stack s1 = new Stack<>();

// Push some elements onto the stack
s1.push(1);
s1.push(2);
s1.push(3);

// Count elements using recursion
int count = countElements(s1);

// Print the count of elements
System.out.println("Number of elements in the stack: " + count);
}

// Recursive method to count elements
public static int countElements(Stack s1) {
if (s1.isEmpty()) {
return 0;
}
// Remove the top element and count the rest
Integer element = s1.pop();
int count = 1 + countElements(s1);
// Push the element back to restore the stack
s1.push(element);
return count;
}
}

Output

Number of elements in the stack: 3

Conclusion

We have explored 3 approaches to count the total number of elements in the stack. The first approach using the Stack.size() method is simple and straightforward. The second approach uses the 'for' loop to count stack elements, which is a little more complex than the first approach. The third approach counts stack elements using the recursion, which can be complex for beginners.


If you need to perform some operations on each element of the stack while counting the stack elements, you should use the second approach.

Shubham B Vora
Shubham B Vora

Expert Technical Content Writer | Specializing in Technology, AI, and Programming | Helping Brands Communicate Effectively

Updated on: 2024-09-10T09:50:50+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements