Printing the stack values in Java

In Java, I want to print the contents of a Stack. The toString() method prints them encased in square brackets delimited by commas: [foo, bar, baz].

How do I get rid of them and print the variables only?

My code so far:

Stack myStack = new Stack ();

for(int j=0; j<arrayForVar.length; j++) {
    if(arrayForVar[j][1] != null) {
        System.out.printf("%s \n", arrayForVar[j][1] + "\n");
        myStack.push(arrayForVar[j][1]);
    }
}

System.out.printf("%s \n", myStack.toString());

This answer worked for me:

Use the toString method on the Stack, and use replaceAll method to replace all instances of square brackets with blankstring. Like this:

System.out.print(
    myStack.toString().replaceAll("\\[", "").replaceAll("]", ""));

Solution 1:

There is a workaround.

You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(myStack.toArray()));

Solution 2:

stack.forEach(System.out::println);

Using Java 8 and later stream functions

Solution 3:

Use the same kind of loop that you used to fill the stack and print individual elements to your liking. There is no way to change the behavior of toString, except if you go the route of subclassing Stack, which I wouldn't recommend. If the source code of Stack is under your control, then just fix the implementation of toString there.

Solution 4:

Another method is the join method of String which is similar to the join method of Python:

"" + String.join("/", stack)

This will return the string containing all the elements of the stack and we can also add some delimiter by passing in the first argument.

Example: Stack has two elements [home, abc]

Then this will return "/home/abc".