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?

3
  • What do you mean, "the result of a method reference?" println is a void method, so obviously you can't pass its result to forEach. Commented Sep 8, 2014 at 15:26
  • I want to print uppercased values. So I want to combine toUpperCase with println Commented Sep 8, 2014 at 15:27
  • "Nice" to get a vote down without explanation. Commented Sep 8, 2014 at 15:45

1 Answer 1

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…

Sign up to request clarification or add additional context in comments.

2 Comments

The Stream is the way how to combine arbitrary operations.
Well, _ is a reserved keyword 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.