0

I make myself familiar with Java 8's so called method references.

Two questions:

1) I want to println uppercased values. How can I pass the result of String::toUpperCase to println? For example this block of code doesn't compile:

List<String> food = Arrays.asList("apple", "banana", "mango", "orange", "ice");
food.forEach(System.out.println(String::toUpperCase));

2) Is there something similar to anonymous function parameters (_) like is Scala?

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Konstantin Milyutin
  • 11,946
  • 11
  • 59
  • 85

1 Answers1

4

What you want to do is to combine a function with a consumer.

You can do it this way:

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

Alternatively you can use a lambda expression:

food.forEach(x->System.out.println(x.toUpperCase()));

Besides these straight-forward approaches, you can combine functions to create a new function but not a function with a consumer, however, with the following quirky code you can do it:

Function<String,String>     f0=String::toUpperCase;
food.forEach(f0.andThen(" "::concat).andThen(System.out::append)::apply);

This get even uglier if you try to inline the first expression for a one-liner…

Holger
  • 285,553
  • 42
  • 434
  • 765
  • The `Stream` *is* the way how to combine arbitrary operations. – Holger Sep 08 '14 at 15:32
  • 2
    Well, [`_` is a reserved keyword](http://stackoverflow.com/questions/23523946/underscore-is-a-reserved-keyword/23525446#23525446) and might be a placeholder for parameters you don’t want to use in a future Java version, however, that doesn’t apply here as here the parameters *are* used. – Holger Sep 08 '14 at 16:03