DEV Community

M. Savic
M. Savic

Posted on

2 2

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!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay