Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the efficient and concise way to construct a String from Character Stack

Tags:

java

stack

java-8

Suppose I have a stack -

O (stack top)
L
L
E
H (stack bottom)

What is the concise way to convert it to "HELLO"

Now I am doing this way -

private static String getString(Stack<Character> charStack) {
  StringBuilder output = new StringBuilder();

  while (!charStack.isEmpty()) {
      output.append(charStack.pop());    
  }

  return output.reverse().toString();
}
like image 736
shakhawat Avatar asked Sep 03 '25 02:09

shakhawat


1 Answers

Using map and Collectors, one way of doing what the code in question intend would be:

return charStack.stream().map(Object::toString).collect(Collectors.joining());

Edit: As visible from comments (1) and (2), if emptying the stack is an intentional action, you can update the code to include the behaviour as follows:

String output = charStack.stream().map(Object::toString).collect(Collectors.joining());
charStack.clear();
return output;
like image 160
Naman Avatar answered Sep 07 '25 17:09

Naman