Reverse String in one line

Yesterday, while scrolling Twitter I stumbled upon this one:

图片[1]-Reverse String in one line - 拾光赋-拾光赋
图片[2]-Reverse String in one line - 拾光赋-拾光赋 30 seconds of code @30secondsofcode
图片[3]-Reverse String in one line - 拾光赋-拾光赋 reverseString: Reverses a string.
#JavaScript
30secondsofcode.org/js/s/reverse-s… 12:30 PM – 27 Apr 2021
图片[4]-Reverse String in one line - 拾光赋-拾光赋
图片[5]-Reverse String in one line - 拾光赋-拾光赋

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!

原文链接:Reverse String in one line

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容