Chapter 5. Issues with Streams, Lambdas, and Method References
Now that you know the basics of lambdas and method references and how they are used in streams, there are several topics that arise from the combination. For example, now that interfaces can have default methods, what happens when a class implements multiple interfaces that have the same default method signature but different implementations? As another example, what happens when you are writing code in a lambda expression and try to access or modify a variable defined outside it? Also, what about exceptions? How are they handled in lambda expressions, where you have no method signature on which to add a throws clause?
This chapter deals with all these issues and more.
5.1 The java.util.Objects Class
Problem
You wish to use static utility methods for null checking, comparisons, and more.
Solution
Use the java.util.Objects class, added in Java 7, but helpful during stream processing.
Discussion
One of the lesser-known classes added in Java 7 is the java.util.Objects class, which contains static methods for a variety of tasks. These methods include:
static boolean deepEquals(Object a, Object b)-
Checks for “deep” equality, which is particularly useful when comparing arrays.
static boolean equals(Object a, Object b)-
Uses the
equalsmethod from the first argument, but is null safe. static int hash(Object... values)-
Generates a hash code for a sequence of input values.
static String toString(Object o)-
Returns ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access