

The if statement filters out elements, the function call maps a rule to the number of errors, and the compound assignment adds each count to an accumulator. Although it might not be obvious, this example is analogous to a filter MapReduce operation. In the example in Figure 11, the total number of errors in a collection of rules is calculated. The IDE can refactor existing external iterators, such as enhanced for loops, to utilize these new internal iterators. Some examples of these operations are MapReduce, filterForEach, and anyMatch, to name a few. Java SE 8 has added several methods to the Collections API that take a lambda expression as an argument and enable functional operations over collections.

The second refactoring, which is shown in Figure 10, highlights another feature of Java SE 8: internal iterators. As you can see in Figure 9, a 1 was appended to the variable name to avoid any errors. The IDE detects variable shadowing and automatically renames shadowing variables to avoid compilation errors. While variable shadowing is legal in anonymous inner classes, lambda expressions do not allow this. In Figure 8, a variable declaration in the anonymous inner class hides or shadows a variable declared in the enclosing scope. If this cast were not added, the resulting lambda expression would be ambiguous, as shown in Figure 7, and a compilation error would result. When you perform the refactoring, the IDE automatically adds a cast to the correct type (see Figure 6). In this method, the doPrivileged method is overloaded and can accept either a PrivilegedAction or a PrivilegedExceptionAction. For example, examine the code snippet in Figure 5. While this transformation might seem simple at first glance, the IDE performs static analysis to ensure that the transformation is performed safely. As you can see in Figure 4, the new syntax is much more concise and easier to read. NetBeans IDE 8 highlights valid refactoring sites (see Figure 3), and when you select the Java hint in the left sidebar, the IDE performs the conversion automatically.

Lambda expressions provide a more concise replacement for anonymous inner classes that declare only a single method. Anonymous inner classes such as the one shown in Figure 2 are useful constructs, although the syntax is unnecessarily verbose.

We’ll start by looking at the first refactoring. The first refactoring converts anonymous inner classes to lambda expressions, and the second refactoring converts for loops that iterate over collections to functional operations that use lambda expressions. NetBeans IDE 8 provides two automated refactorings that leverage this new language feature. Originally published in the May/June 2014 issue of Java Magazine.
