There is no point in converting
list.forEach(s -> {
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
});
to
list.forEach({
System.out::println(String::toLowerCase);
System.out::println(String::toUpperCase);
});
as there is no win in clarity, the latter even consists of more characters than the former, if we use the same indention and insert the Upper
you have left off the second variant. So why should we have such an alternative form?
Method reference have been invented as a feature allowing a dense syntax for a single method delegation, were declaring and referencing the parameters could really make a difference. Even replacing a sole s->System.out.println(s)
with System.out::println
is no that big win, but at least, there is some. Further, encoding the method reference at bytecode level can be more compact because the target method can be directly referenced just like the synthetic method holding a lambda expression’s code. For compound method references, there is no such compact form.
Since your desired operation consist of operations of different kinds, you may use the Stream
API, which is intended to combine such operations:
list.stream().flatMap(s->Stream.of(s.toLowerCase(), s.toUpperCase()))
.forEach(System.out::println);
and if you want to include method references for everything, at all costs, you may do it the following way:
list.stream()
.flatMap(s->Stream.<UnaryOperator<String>>of(String::toLowerCase, String::toUpperCase)
.map(f->f.apply(s)))
.forEach(System.out::println);