Answer the question
In order to leave comments, you need to log in
How to invert strings in an array by implementing the Function interface?
The task is as follows: to implement the Function interface, where the input is an array of strings, and the output should be an array of inverted strings. If this were a normal implementation, there would be a lot of opportunities to expand through the array and through the StringBuilder and in general. And I don’t understand how to return at once in functional programming, perhaps due to the fact that I didn’t fully understand the topic.
I built some structure like this:
Function<String[], String[]> reverseString = input -> {
};
Answer the question
In order to leave comments, you need to log in
Functional programming is about applying a sequence of functions to arguments (and about higher-order functions). In general, if you touched on functional programming and array lists, then start looking at StreamAPI, this is the most functional thing in Java. In general, functional programming in Java is not so good, if this topic is interesting - go to Kotlin (or Scala, but Scala is practically not used in industrial programming).
Your problem can be solved, for example, like this:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Arrays.stream(args).map(Main::reverse).forEach(System.out::println);
}
private static String reverse(String s) {
final StringBuilder result = new StringBuilder();
for (char c : s.toCharArray()) {
result.insert(0, c);
}
return result.toString();
}
}
I mean, what's wrong with that? You have a method that takes String[] input as input, and should return an array of String[] but with inverted strings. That is exactly the same as what you would write if it were like this:
public String[] reverseString(String[] input) {
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question