×

Java Programs

Java Practice

Java program to add an ArrayList into Stack collection

Java example to add an ArrayList into Stack collection.
Submitted by Nidhi, on April 26, 2022

Problem statement

In this program, we will create a Stack Collections, ArrayList with a few elements. Then we will add an ArrayList into another Stack collection using the addAll() method.

Java program to add an ArrayList into Stack collection

The source code to add an ArrayList into the Stack collection is given below. The given program is compiled and executed successfully.

// Java program to add an ArrayList into 
// Stack collection

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) {
    Stack < Integer > stack = new Stack < Integer > ();

    stack.push(10);
    stack.push(20);
    stack.push(30);
    stack.push(40);

    System.out.println("The Stack is: " + stack);

    ArrayList < Integer > arrList = new ArrayList < Integer > ();
    arrList.add(50);
    arrList.add(60);
    arrList.add(70);
    arrList.add(80);

    stack.addAll(arrList);

    System.out.println("The Stack is: " + stack);
  }
}

Output

The Stack is: [10, 20, 30, 40]
The Stack is: [10, 20, 30, 40, 50, 60, 70, 80]

Explanation

In the above program, we imported the "java.io.*" and "java.util.*" packages to use the Stack collection class. Here, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.

In the main() method, we created a Stack collection and an ArrayList. Then we added ArrayList into the Stack collection using the addAll() method and printed the result.

Java Stack Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.