Yesterday, while scrolling Twitter I stumbled upon this one:
30 seconds of code@30secondsofcodereverseString: Reverses a string. #JavaScript 30secondsofcode.org/js/s/reverse-s…12:30 PM - 27 Apr 2021
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);
}
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<>();
}
});
}
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)
Cool! Collector is very powerful.
I think the easiest way to reverse a string is to use a StringBuilder like this: