Month: May 2014

The effects of programming with Java 8 Streams on algorithm performance

Multi-paradigm programming with Java has been possible for many years, with its support for a mix of service oriented, object oriented and aspect oriented programming. Java 8 with its lambdas and class, is good news because it lets us add the functional programming paradigm into the mix. Indeed there has been a lot of hype around lambdas. But is changing our habits and the way we write our code a wise thing, without first getting to know the dangers that might lurk? Java 8's Stream class is neat because it lets you take a collection of data and chain multiple functional calls on that data together, making for tidy code. Map/reduce algorithms are a good example, where you take a collection of data and aggregate it by first selecting or modifying data out of a complex domain and simplifying it (the "map" part), and then reducing it to a single useful value. Take for example the following data classes (written in Groovy so that I get code generation of constructors, accessors, hash/equals and toString methods for free!): //Groovy @Immutable class City { String name List<Temperature> temperatures } @Immutable class Temperature { Date date BigDecimal reading } I can use those classes to construct some random weather data in a list of City objects, e.g.: private static final long ONE_DAY_MS = 1000*60*60*24; private static final Random RANDOM = new Random(); public static List<City> prepareData( int numCities, int numTemps) { List<City> cities = new ArrayList<>(); IntStream.range(0, numCities).forEach( i -> cities.add( new…

Read more