2

I have the following list. I'd like to print the values using lambda and method reference. The first lambda expression works, but I have no idea how to print the values using the method reference, because I am getting the compilation error.

List<String> letters = Arrays.asList("a","b","c");

System.out.println("Lambda upperCase forEach");
letters.forEach(l -> System.out.println(l.toUpperCase))); //it works

System.out.println("Method Reference upperCase forEach");
letters.forEach(System.out::println(String::toUpperCase)));  //compilation error

How to print the values using method reference?

Beti
  • 175
  • 2
  • 10
  • 1
    in method references you just give the name of the function (println), they don't take arguments. You can create your own function that accepts a string and calls toUpperCase and then println, and then give the name of your function as the method reference name. – Gonen I Mar 19 '21 at 19:11
  • writing `System.out::println()` is a non sense since you are calling a member from a namespace (should look at C++ namespaces). (add missing parenthesis after `l.toUpperCase` line 4) – midugh Mar 19 '21 at 19:28

3 Answers3

7

When using method reference, you can't pass parameterized arguments. Instead try to convert the values to uppercase first and then print the value as below,

letters.stream().map(String::toUpperCase).forEach(System.out::println);

The map method will convert the values to upper case and the forEach method will print the values.

Vimukthi
  • 846
  • 6
  • 19
2

While I actually prefer Vimukthi_R's answer above, here is an alternative. You can create your own function that accepts a string and calls toUpperCase and then println, and then give the name of your function as the method reference name:

Bottom line in Java, method references don't take arguments, and in fact don't even take an empty argument list. ()

public class Example {
    public static void printUpperCase(String s)
    {
        System.out.println(s.toUpperCase());
    }
    public static void main(String[] args) {
        Arrays.asList("a","b","c").forEach(Example::printUpperCase);
    }
}
Gonen I
  • 5,576
  • 1
  • 29
  • 60
2
letters.forEach(System.out::println(String::toUpperCase));

does not compile, because method references accept argument(s) implicitly, if the methods they refer to, define such, and you cannot pass them explicitly.

Even if explicit arguments were allowed, none of the println() overloads, in PrintStream, takes another method reference, as an argument.

letters.stream()
    .map(String::toUpperCase)
    .forEach(System.out::println);

would:

  1. get the stream object from your letters;
  2. map stream objects to their respective objectს (think of it as a transformation of objects, in the stream pipeline);
  3. and finally, pass each element of the stream into the method, referenced by System.out::println.
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66