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();
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With