Every Friday, we’re showing you a couple of nice new tutorial-style Java 8 features, which take advantage of lambda expressions, extension methods, and other great stuff. You’ll find the source code on GitHub.
Java 8 Goodie: Lambdas and XML
There isn’t too much that Java 8 can do to the existing SAX and DOM APIs. The SAX ContentHandler has too many abstract methods to qualify as a @FunctionalInterface, and DOM is a huge, verbose API specified by w3c, with little chance of adding new extension methods.
Luckily there is a small Open Source library called jOOX that allows for processing the w3c standard DOM API through a wrapper API that mimicks the popular jQuery library. jQuery leverages JavaScript’s language features by allowing users to pass functions to the API for DOM traversal. The same is the case with jOOX. Let’s have a closer look:
Assume that we’re using the following pom.xml
Let’s assume we wanted to know all the involved artifacts in Maven’s groupId:artifactId:version notation. Here’s how we can do that with jOOX and lambda expressions:
We can also transform the XML content. For instance, if the target document doesn’t need to be a POM, we could replace the matched groupId elements by an artifical artifact element that contains the artifact name in Maven notation. Here’s how to do this:
The above puts new content in place of the previous one through .content(), and then renames the groupId elements to artifact, before printing out the element. The result is:
What becomes immediately obvious is the fact that the lambda expert group’s choice of making all SAMs (Single Abstract Method interfaces) eligible for use with lambda expressions adds great value to pre-existing APIs. Quite a clever move.
But there are also new APIs. Last week, we have discussed how the existing JDK 1.2 File API can be improved through the use of lambdas. Some of our readers have expressed their concerns that the java.io API has been largely replaced by java.nio (nio as in New I/O). Next week, we’ll have a look at Java 8’s java.nnio API (for new-new I/O ;-) ) and how it relates to the Java 8 Streams API.