0

Given a string, what is the simplest way in Java-8 to convert it to a stack of charactes using the streams and collectors APIs?

apophis
  • 374
  • 3
  • 11
  • 2
    Convert to a stream of ints via `chars()` or `codePoints()`, and go from there. – Brian Goetz Nov 03 '16 at 16:26
  • 1
    See also http://stackoverflow.com/questions/26320910/how-to-convert-a-string-to-a-java-8-stream-of-characters and [that answer](http://stackoverflow.com/a/31641308/1743880) and this as well (for `Collectors.toCollection`) http://stackoverflow.com/questions/21522341/collection-to-stream-to-a-new-collection – Tunaki Nov 03 '16 at 16:31
  • The main point is not how to get the characters of the string it self but how to collect it to a deque-stack using the collector API. I change the question to focus in this main point. –  Nov 03 '16 at 16:36
  • This wasn't clear at all reading the question. But [the last link](http://stackoverflow.com/questions/21522341/collection-to-stream-to-a-new-collection) is what you're looking for then `.collect(Collectors.toCollection(Stack::new))`. – Tunaki Nov 03 '16 at 16:40
  • Note that a collection of boxed Ints has a lot of overhead, you might want to use an `int[]` instead – the8472 Nov 03 '16 at 16:52
  • I reach this code according to your advices: `Deque stack = s.chars().mapToObj(c -> (char) c).collect(Collectors.toCollection(ArrayDeque::new));` . Is this the best way to avoid boxing ? –  Nov 03 '16 at 16:56
  • You don’t avoid boxing; your task inherently bears boxing. You should ask yourself why you need a `Deque` at all. – Holger Nov 03 '16 at 17:10
  • The stack will be a good data structure to handle some tasks such as parse expressions with brackets characters. –  Nov 03 '16 at 17:20
  • 2
    That stack doesn’t offer anything you couldn’t do with the original `String` and an `int` position, as backtracking doesn’t require the capability to push arbitrary objects, but rather a simple way to reset the position. You can write a wrapper class encapsulating the `String` and `int` position for that, though even that [already exists](https://docs.oracle.com/javase/8/docs/api/java/nio/CharBuffer.html#wrap-java.lang.CharSequence-)… – Holger Nov 03 '16 at 17:26

0 Answers0