javamethod-reference

Why i cant use StringBuilder::reverse in as method reference to reverse a string?


Why i cant use StringBuilder::reverse in as method reference to reverse a string? please help make me understand whats going on under the hood.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.UnaryOperator;

public class Main {
    public static void main(String[] args) {
        Random random = new Random();

        String[] names = {
                "MEmarGya", "KaandHoGYa",
                "lmaodEd", "OmFOOF",
                "lakshayGulatiOP", "deEpAkKaLaL"
        };

        List<String> namesList = Arrays.asList(names);

        ArrayList<UnaryOperator<String>> operators = new ArrayList<>();
        operators.add(s -> s.toUpperCase());
        operators.add(String::toUpperCase);

        operators.add(s -> s + s.charAt(random.nextInt(0, s.length())));

        operators.add(s -> s + ' ' + new StringBuilder(s).reverse());
        operators.add(StringBuilder::reverse); //<------ Here

        for (UnaryOperator<String> operator: operators) {
            namesList.replaceAll(operator);
            System.out.println(Arrays.toString(names));

        }


    }
}

err occured:

java: incompatible types: invalid method reference method reverse in class java.lang.StringBuilder cannot be applied to given types required: no arguments found: java.lang.String reason: actual and formal argument lists differ in length


Solution

  • You can only add UnaryOperator<String> instances to the operators List. This means you need a method that accepts a String and returns a String.

    But you try to add the method reference - StringBuilder::reverse - which is a method that accepts a StringBuilder and returns a StringBuilder, and therefore conforms with UnaryOperator<StringBuilder>.

    You can still use that method with a lambda expression, that will accept a String, convert it to StringBuilder, reverse it, and convert back to String:

    operators.add(s -> new StringBuilder(s).reverse ().toString ());