DEV Community

M. Savic
M. Savic

Posted on

Reverse String in one line

Yesterday, while scrolling Twitter I stumbled upon this one:


At first, I was amazed how much JavaScript has changed since the last time I tried it. Spread operator and useful methods directly on array objects are something that I am missing in Java.
Naturally being a Java dev, as I was looking at JS code I tried to transpile it to Java code. Initial code would look something like this:
public String reverse(String in){
    String[] split = in.split("");
    Collections.reverse(Arrays.asList(split));
    return String.join("", split);
}
Enter fullscreen mode Exit fullscreen mode

This works but this is more than one line. To produce oneliner I started looking at Java Stream API and its methods. While I was aware that all intermediate operations are out of the question for such a task, I started looking at available Collectors.
My search came back empty and I had to resort to implementing custom Collector:

public String reverse(String in){
    return Arrays.stream(in.split("")).collect(new Collector<String, List<String>, String>() {
        final List<String> helper = new LinkedList<>();
        @Override
        public Supplier<List<String>> supplier() {
            return () -> helper;
        }

        @Override
        public BiConsumer<List<String>, String> accumulator() {
            return (strings, s) -> strings.add(0, s);
        }

        @Override
        public BinaryOperator<List<String>> combiner() {
            return null;
        }

        @Override
        public Function<List<String>, String> finisher() {
            return strings -> String.join("", strings);
        }

        @Override
        public Set<Characteristics> characteristics() {
            return new HashSet<>();
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

There it is! Technically it's a oneliner. Our supplier method is a simple list, when we add a new item to the list we always do it at the beginning of the list as in the accumulator method. The finisher combines a list into a resulting String. We don't implement combiner because parallel streams are not ordered and we cannot lose the initial string order.
Of course, this is overkill and I did it just for fun, but I got to admit how powerful the Collector API is.
Do you have another way of writing this method? Write it in the comments! Thanks for reading!

Top comments (1)

Collapse
 
wldomiciano profile image
Wellington Domiciano

Cool! Collector is very powerful.

I think the easiest way to reverse a string is to use a StringBuilder like this:

public static String reverse(String str) {
  return new StringBuilder(str).reverse().toString();
}
Enter fullscreen mode Exit fullscreen mode