-1

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

LakshayGMZ
  • 51
  • 5
  • 1
    `StringBuilder::reverse` is not a *function that takes and returns a string*. So why would you expect it to be usable as a `UnaryOperator`? – khelwood Apr 30 '23 at 08:54
  • And from an intuitive perspective, `reverse` is not a method of `String` ... so why would you can call it on a `String` object ... by any means? – Stephen C Apr 30 '23 at 09:08

1 Answers1

3

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 ());
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Eran
  • 387,369
  • 54
  • 702
  • 768