13

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("]", ""));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Armani
  • 151
  • 1
  • 2
  • 6
  • I suspect half the code you have doesn't do what you want. Can you simplify your example? Why are you using a `Stack` at all? – Peter Lawrey Aug 28 '12 at 13:24
  • Hi Lads, I appreciate everyone's help, i guess I found what i need, the answer to my question is as follows: `System.out.print(myStack.toString().replaceAll("\\[", "").replaceAll("]", ""));` – Armani Aug 28 '12 at 15:04
  • why you put // for [ and don't for ]? – Hengameh May 19 '15 at 02:36
  • Thanks Armani! That helped me. You should rewrite your update (to your question) as the answer and accept it. Then I would up vote that too! – Joe Dec 16 '15 at 19:30

11 Answers11

15

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()));

John Eipe
  • 10,922
  • 24
  • 72
  • 114
  • its from http://stackoverflow.com/questions/395401/printing-java-collections-nicely-tostring-doesnt-return-pretty-output – John Eipe Aug 28 '12 at 13:37
6
stack.forEach(System.out::println);

Using Java 8 and later stream functions

JesseBoyd
  • 1,022
  • 1
  • 13
  • 18
3

Use toArray() to print the stack values

public void printStack(Stack<Integer> stack) {

    // Method 1:
    String values = Arrays.toString(stack.toArray());
    System.out.println(values);

    // Method 2:
    Object[] vals = stack.toArray();
    for (Object obj : vals) {
        System.out.println(obj);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter
  • 31
  • 1
2

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VR7
  • 112
  • 3
  • 16
0

From documentation of toString() method of AbstractCollection. So you can not do it unless you define your own StackOr implement custom toString() by iterating over Stack

public String toString()

Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

This implementation creates an empty string buffer, appends a left square bracket, and iterates over the collection appending the string representation of each element in turn. After appending each element except the last, the string ", " is appended. Finally a right bracket is appended. A string is obtained from the string buffer, and returned.

Community
  • 1
  • 1
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
0

Throwing a suggestion into the pool here. Depending on your Stack implementation this may or may not be possible.

The suggestion is an anonymous inner class for overriding the toString() in this particular case. This is one way to locally implement the subclassing Marko is mentioning. Your Stack instantiation would look something like

Stack s = new Stack(){
              public String toString(){
                 // query the elements of the stack, build a string and
                 return nicelyFormattedString;
              }
          };
...
Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
0
while(!myStack.isEmpty()) {
    System.out.print(myStack.pop());
}

You will print the first element of the stack and pop it, repeating until the stack is empty

0

Using string builder

StringBuilder result = new StringBuilder()
while(!myStack.isEmpty())result.append(myStack.pop());
System.out.print(result.reverse().toString())
Ketan sangle
  • 376
  • 5
  • 6
-2

Try this:

 System.out.println(Arrays.asList(stackobject.toArray()));
 System.out.println(Arrays.toString(stackobject.toArray()));
C B
  • 1,677
  • 6
  • 18
  • 20
-2
 Stack <String> Cars=new Stack();
 Cars.push("Lambo Urus");
    Cars.push("Honda Civic");
    Cars.push("Ford Mustang");

   while(!Cars.isEmpty()){
                System.out.println(Cars.pop());
            }
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Jan 16 '22 at 10:56