Lambda expressions - part 1

With the arrival of Java 8, new functionality has been added to the Java libraries.
One of the new features is the addition of the Lambda expressions, Java's first step into functional programming.
But, you must be guessing, what is a Lambda expression? It is a function than can be created without belonging to any class. A Lambda expression can be passed around as if it was an object (imagine an anonymous object) and executed on demand.
But enough words, let's cut to the chase.

If you been around in Java for some years - like me - , when you needed to iterate through a Collection (say, a List) you would normally use an enhanced for loop :

public void test(){
    List<String> names = new ArrayList<String>();
         names.add("Peter");
         names.add("Phil");
         names.add("Tony");
         names.add("Mike");
         names.add("Steve");

   for(String name:names){ 
       System.out.println("Name: " + name);
   }
}

Or you would even use the "classic" loop:

public void test(){
    List<String> names = new ArrayList<String>();
    
    names.add("Peter");
    names.add("Phil");
    names.add("Tony");
    names.add("Mike");
    names.add("Steve");
     
    for(Iterator<String> nameIterator = names.iterator(); 
          nameIterator.hasNext();){
         System.out.println("Name: " + nameIterator.next()); 
    }
}

But since the addition of the lambda expressions, now we can do this:

public void test(){
    
     List<String> names = new ArrayList<String>();
     names.add("Peter");
     names.add("Phil");
     names.add("Tony");
     names.add("Mike");
     names.add("Steve");
    
    names.forEach(name -> System.out.println(name));
}

The output:
Peter
Phil
Tony
Mike
Steve


Do you spot how simple is now to loop through a collection ? But this is just beginning. As you can see the .forEach() method (implemented through the Iterable interface) let you perform an action (in this case printing the names).

There are a lot of functions we can add on the same expression. For example, we can obtain a sublist of the original one, with only the names starting with "P".
public void test(){
    List<String> names = new ArrayList<String>();
    

      names.add("Peter");
      names.add("Phil");
      names.add("Tony");
      names.add("Mike");
      names.add("Steve");

      names.stream().filter(name -> 
         name.startsWith("P")).collect(Collectors.toList()).forEach(name ->       System.out.println("Name: " +name));
}

This is the output
Name: Peter
Name: Phil

In this case we use aggregate operations: these operations process elements from a stream, not directly from a collection. In the example above the aggregate operations accept lambda expressions with parameters. 

That's it for now!


Comments

Popular Posts