Java 8 — Just a little “hands on” 1

**moved from medium.com

I’m looking around and seeing many people working with older versions of Java.. then i will write some articles to stimulate this upgrade, to take doubts or discussions.

Let’s start in my first Medium article with a common practice.. a loop with FOR EACH.

Below you will take the old foreach:

List<Book> books = Arrays.asList(book1, book2, book3);for(Book u : books){
   System.out.println(b.getName());
}

Arrays.asList is a easy way to create an immutable List.

Now we can do for eachs with the new method of collections, forEach:

books.forEach(…);

This method receive a type java.util.function.Consumer with a unique method accept. This is from the new package java.util.function.

Let’s create this consumer, before use the new forEach:

class Display implements Consumer<Book> {
    public void accept(Book b){
      System.out.println(b.getName());
    }
}

Then we can do it:

Display display = new Display();
usuarios.forEach(display);

But, for this we can use anonymous classes like a good practice to simple tasks like that:

Consumer<Book> display = new Consumer<Book>() {
   public void accept(Book b){
      System.out.println(b.getName());
   }
};books.forEach(display);

Now it’s better! But, the code is still bigger, let’s change one more time:

books.forEach(new Consumer<Book>() {
   public void accept(Book b){
     System.out.println(b.getName());
   }
});

Yeah! Now we have the same, but not so verbose..

Hello, LAMBDA!

Now let’s know the lambda, this is it the Java simple way to implements an interface with ONLY ONE method. (Remember what we talk about the java.util.function.Consumer) 🙂

Consumer<Book> display = (Book b) -> {System.out.println(b.getName());};

WTF?! yes.. this is the same forEach! 😀

(Book b) -> {System.out.println(b.getName());}; 
//it’s a Java 8 lambda.

The compiler knows how to infer the type, and if the block have only one instruction we can remove the { }.

Consumer<Book> display = b -> System.out.println(b.getName());

What? A foreach on 1 line? Better… we don’t need a temporary variable.

books.forEach(b -> System.out.println(b.getName()));

It’s this.

Easy? EASY and CLEAN.

I will continue more explanations about Java 8, if you have any idea to share, tell me.
Thank you.

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 )

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

Comments (

0

)

Create a website or blog at WordPress.com

%d bloggers like this: