Re: are lambdas a way to bring functional programming to java?
On Fri, 27 Jun 2014 16:50:44 -0700 (PDT), gdotone@gmail.com wrote,
quoted or indirectly quoted someone who said :
how does it make the program more readable?
// create a new HashMap
final Map<String, Integer> h = new HashMap<>( 149 /* capacity
*/, 0.75f /* loadfactor */ );
{
// add some key/value pairs about English measure to the
HashMap
h.put( "inch", 1 );
h.put( "foot", 12 );
h.put( "yard", 36 );
h.put( "mile", 3760 * 36 );
}
Compare old style enumerating a HashMap
out.println( "enumerate all the key/value Entries in the HashMap" );
for ( Map.Entry<String, Integer> entry : h.entrySet() )
{
// prints lines of the form foot=12
// in effectively random order.
// this does not require an expensive get lookup to find
the value
String key = entry.getKey();
int value = entry.getValue();
out.println( "separately: " + key + " " + value );
}
Lambda style:
out.println( "enumerate all the key/value Entries in the HashMap
using Java 1.8 lambda dual foreach" );
h.forEach( ( unit, measure ) -> {
out.println( unit + " -> " + measure );
// this effectively creates an anonymous class with an
anonymous method that prints two values.
// h.forEach traverses the hasMap and calls that method
for each key/value pair.
// Javac automatically infers the types from the
declaration for h.
--
Roedy Green Canadian Mind Products http://mindprod.com
The art of strongly-typed language design is largely arranging
that errors are automatically detected as soon as possible
in the compose, compile, run cycle.