Java Reference
In-Depth Information
* @param consume Whether the element should be consumed after being
* returned.
* @return {@link java.util.Optional#empty()} if there are no other elements;
* otherwise, an {@link java.util.Optional} containing the next
* element. Never {@code null}.
*/
Optional<E> nextElement(boolean consume);
@Override
default boolean hasNext() {
return nextElement(false).isPresent();
}
@Override
default E next() {
return nextElement(true).orElseThrow(
() -> new NoSuchElementException("Iterator is exhausted")
);
}
}
Static Methods
It's not directly related to lambdas, but now is a good time to mention it: as of Java 8, interfaces can also now
provide static methods, just as any concrete or abstract class could provide static methods. If you want to
provide a default method implementation to the outside world, you can use a static method to do so: simply
have the default method call the static method.
Now that interfaces can have static methods, some Java interfaces have been extended to provide
utility methods. The most notable to my mind is Comparator , which has picked up a large number of utility
methods. For instance, in Listing 2-25, we define a Comparator that puts null File instances last and sorts
the rest by file name. By allowing static methods, Java 8 has outdated the “utility class” convention, where
an interface Foo would have utility class Foos or FooUtils . Now those utility methods reside directly on the
interface itself.
Listing 2-25. Using Comparator Static Methods to Generate a Comparator
Comparator<File> fileComparator =
Comparator.nullsLast(
Comparator.comparing(File::getName)
);
Functional Interface Helper Methods
The functional interfaces themselves carry a number of static and default methods to help you build the
functions that you are looking for. Through this section, we will look at those methods, and get a sense as to
when and why you want to use them.
 
Search WWH ::




Custom Search