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
equals
method 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 ...
Get Modern Java Recipes now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.