Java Reference
In-Depth Information
Table 3.3. Examples of lambdas with functional interfaces
Use case
Example of lambda
Matching functional interface
A
boolean
(List<String> list) -> list.isEmpty()
Predicate<List<String>>
expression
Creating objects
() -> new Apple(10)
Supplier<Apple>
Consuming from
(Apple
a)
->
Consumer<Apple>
an object
System.out.println(a.getWeight())
Select/extract
(String s) -> s.length()
Function<String,
Integer>
or
from an object
ToIntFunction<String>
Combine
two
(int a, int b) -> a * b
IntBinaryOperator
values
Compare
two
(Apple
a1,
Apple
a2)
->
Comparator<Apple>
or
objects
a1.getWeight().compareTo
BiFunction<Apple, Apple, Integer> or
(a2.getWeight())
ToIntBiFunction<Apple, Apple>
What about exceptions, lambdas, and functional interfaces?
Note that none of the functional interfaces allow for a checked exception to be thrown. You have
two options if you need a lambda expression to throw an exception: define your own functional
interface that declares the checked exception, or wrap the lambda with a try/catch block.
For example, in section 3.3 we introduced a new functional interface Buffered-ReaderProcessor
that explicitly declared an IOException:
@FunctionalInterface
public interface BufferedReaderProcessor {
String process(BufferedReader b) throws IOException;
}
BufferedReaderProcessor p = (BufferedReader br) -> br.readLine();
Search WWH ::




Custom Search