Java Lambdas : Syntactic Sugar

You glance down at your list of invited guests for your party.
Suddenly, you see someone with the last name of “Dang”, the very same family that ruined your party the last time they showed up.

Furiously, you write a program to sort through the hundreds of invited guests to remove everyone with the last name “Dang”.

For the sake of simplicity, a smaller list will be used, but nonetheless, you end up with this hideous snippet:

public class Party {

    static List invitedGuests;

    public static void main(String[] args){

        invitedGuests = new ArrayList() {{
	    add("Henry Dang");
            add("Joe Dang");
	    add("Kevin Smith");
	    add("John Dang");
	    add("John Doe");
	    add("Michelle Sans");
        }};

	for(Iterator iterator = invitedGuests.iterator(); iterator.hasNext();){
            String guestName = iterator.next();

	    if(guestName.contains("Dang")){
                iterator.remove();
	    }
	}

	for(String guests : invitedGuests){
	    System.out.println(guests);
	}
    }
}

 

What a terribly cluttered mess!

But what if you could have done it in a simpler, more concise way?
With Java 8’s lambdas, you can cut down the length of the logic to 1/5th of its size!

public class Party {

    static List invitedGuests;

    public static void main(String[] args){

        invitedGuests = new ArrayList() {{
	    add("Henry Dang");
            add("Joe Dang");
	    add("Kevin Smith");
	    add("John Dang");
	    add("John Doe");
	    add("Michelle Sans");
        }};

     invitedGuests.removeIf(name -> name.contains("Dang"));
     invitedGuests.forEach(name -> System.out.println(name));
    }
}

Just like that, your code instantly becomes clean, concise, and expressive.
The removeIf method simply takes a Predicate, which is basically a boolean. It checks if the name contains the word “Dang” in it, and if it does, it instantly removes it from the list.

The line after it is just a fancy for each loop, except it’s only one line long. The forEach method takes in a Consumer object, which basically says, “Give me a parameter, and something to do with that parameter.” You pass in the parameter “name”, and print all the names in the list.

Now that you’re done, all the Dangs are off your list, and you’ve shortened your otherwise obnoxiously verbose code by 8 lines.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s