[Java 8] – ForEach for interations

Below you can see an exemple how it works.

@Test
public void myTestWithForEachOnly(){

    // Create the list and itens
    List<String> myList = new ArrayList<String>();
    myList.add("text Z");
    myList.add("text B");
    myList.add("text C");

    Consumer myConsumer = new PrintTexts();
    myList.forEach(myConsumer);
}

// Here you define what is to do for each item in the List
public class PrintTexts implements Consumer<String>{
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
}

Result in Console

Screen Shot 2016-06-04 at 5.00.17 PM

Now the same code but better 😛 With lambdas

@Test
public void myTestWithForEachAndLambdas(){
    List<String> myList = new ArrayList<String>();
    myList.add("text Z");
    myList.add("text B");
    myList.add("text C");

    myList.forEach(words.forEach(s -> System.out.println(s));
}

 

 

 

 

 

 

 

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 )

Google+ photo

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

Connecting to %s