Item 45: Use streams judiciously

Introduction Streams in Java 8 support functional-style operations on streams of elements. This API makes it easier to perform bulk operations, sequentially or in parallel. When used appropriately, streams can make programs shorter and clearer. When used inappropriately, they can make programs difficult to read and maintain. When to use streams? Streams are a good

Read More

Item 43: Prefer method references to lambdas

Introduction Method references are more concise than lambdas. If method references are shorter and clearer, use them; otherwise, utilize lambdas. Method references reduce the boilerplate code and thus improves readability. There are four kinds of method references, which are summarized below: Kind Example Reference to a static method ContainingClass::staticMethodName Reference to an instance method of

Read More

Item 44: Favor the use of standard functional interfaces

If one of the standard functional interfaces does the job, you should generally use it in preference to a purpose-built functional interface This will make your API easier to learn, by reducing its conceptual surface area, and will provide significant interoperability benefits Always annotate your functional interfaces with the @FunctionalInterface annotation @FunctionalInterface annotation is used

Read More

Item 42: Prefer lambdas to anonymous classes

Anonymous classes were adequate for the classic objected-oriented design patterns requiring function objects. Here’s a code snippet using an anonymous class. // Anonymous class instance as a function object – obsolete! Collections.sort(words, new Comparator<String>() { public int compare(String s1, String s2) { return Integer.compare(s1.length(), s2.length()); } }); Interfaces with a single abstract method are now

Read More