Evolution of functional programming in Java

For many years I performed most of my data manipulation in Wolfram Mathematica.
With broad support for functional programming, it was nice and simple to apply a function on any arbitraty vector or matrix. The resultant code was really nice and short. A “for” loop was very rarely needed. Having switched to Java 6 and 7, I find such manipulations with data substantially less pleasant. Given the standard packages of Java 7, a “for” loop is unavoidable and the code becomes substantially longer.
Google Guava partially solves the problem with method like “Lists.transform“.
However, in this case the function still has to be explicitly defined.
Let me illustrate the transition on the example of parsing search results in Youtube API. Java 7 code

List<String> videoIds = new ArrayList<>();
for(SearchResult searchResult: searchListResponse.getItems())

Java 7 code with functional programming in Guava:

Function<SearchResult, String> func = new Function<SearchResult, String>() {
            public String apply(SearchResult searchResult) {
                  return searchResult.getId().getVideoId();
List<String> videoIds Lists.transform(searchListResponse.getItems(), func);

The code became longer and less transparent rather than becoming simpler. This is a known caveat in working with Google Guava under Java 6 and 7.
Luckily, Java 8 brings such needed simplications making the above code truly a one-liner.
Lambda expressions save the day

List<String> videoIds = 
   Lists.transform(searchListResponse.getItems(), d -> d.getId().getVideoId());

A simple method can instead be passed as a method reference

List<ResourceId> resourceIds = 
        Lists.transform(searchListResponse.getItems(), SearchResult::getId);

One thought on “Evolution of functional programming in Java

  1. Уou reallly mɑke it aρpear reakly easy ᴡith yur presentatin however I iin finding thіs matter tߋ
    be really one thibg thatt I think І woᥙld by no means understand.
    ӏt sort ⲟf feels tⲟo complicated andd extremely broad
    fⲟr me. I am havinmg a look forward in your next
    publish, Ι’ll try tⲟ get the grasp of it!

Leave a Reply

Your email address will not be published. Required fields are marked *