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())
videoIds.add(searchResult.getId().getVideoId());
Java 7 code with functional programming in Guava:
Function<SearchResult, String> func = new Function<SearchResult, String>() {
@Override
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);