Java 8 forEach examples

Category : Java | Sub Category : Java 8 Features | By Runner Dev Last updated: 2020-09-29 18:55:35 Viewed : 283


Java 8 forEach examples:

Syntax:

@param action The action to be performed for each element

     * @throws NullPointerException if the specified action is null

     * @since 1.8

     */

    default void forEach(Consumer<? super T> action) {

        Objects.requireNonNull(action);

        for (T t : this) {

            action.accept(t);

        }

    }

1. forEach and Map:

   1.1 Before Java 8 : way to loop a Map.

 


Example :

  JavaMapTest .java 

import java.util.HashMap;

import java.util.Map;

 

public class JavaMapTest {

     public static void main(String[] args) {

           Map<String, Integer> animals = new HashMap<>();

           animals.put("Ant", 110);

           animals.put("Bat", 120);

           animals.put("Cat", 130);

           animals.put("Dog", 140);

           animals.put("Elephant", 150);

           animals.put("Fox", 160);

 

           for (Map.Entry<String, Integer> entry : animals.entrySet()) {

                System.out.println("Animal : " + entry.getKey() +

                           " Number : " + entry.getValue());

           }

 

     }

 

}


OutPut:

Animal : Bat Number : 120

Animal : Ant Number : 110

Animal : Cat Number : 130

Animal : Elephant Number : 150

Animal : Dog Number : 140

Animal : Fox Number : 160


1.2 In Java 8 -> loop a Map with forEach with lambda expression


Syntax : 
void java.util.Map.forEach(BiConsumer<? super String, ? super Integer> action) 
The default implementation is equivalent to, for this map: 
 for (Map.Entry<K, V> entry : map.entrySet())
     action.accept(entry.getKey(), entry.getValue());

 

Example : JavaMapTest .java

  

 import java.util.HashMap;

import java.util.Map;

 

public class JavaMapTest {

     public static void main(String[] args) {

           Map<String, Integer> animals = new HashMap<>();

           animals.put("Ant", 110);

           animals.put("Bat", 120);

           animals.put("Cat", 130);

           animals.put("Dog", 140);

           animals.put("Elephant", 150);

           animals.put("Fox", 160);

           System.out.println("forEach1=>");

           animals.forEach((kv) -> System.out.println("Animal : " + k + "Number : " + v));

           System.out.println("forEach2=>");

           animals.forEach((kv) -> {

                System.out.println("Animal : " + k + " Number : " + v);

                if ("Dog".equals(k)) {

                      System.out.println("Different types of dog sounds");

                }

           });

 

     }

 

}


OutPut:

forEach1=>

Animal : BatNumber : 120

Animal : AntNumber : 110

Animal : CatNumber : 130

Animal : ElephantNumber : 150

Animal : DogNumber : 140

Animal : FoxNumber : 160

forEach2=>

Animal : Bat Number : 120

Animal : Ant Number : 110

Animal : Cat Number : 130

Animal : Elephant Number : 150

Animal : Dog Number : 140

Different types of dog sounds

Animal : Fox Number : 160

2. forEach and List:

2.1 Before Java 8 : for-loop to loop a List

Example: JavaListTest .java

 

 import java.util.ArrayList;

import java.util.List;

 

public class JavaListTest {

      

     public static void main(String[] args) {

           List<String> animals = new ArrayList<>();

           animals.add("Ant");

           animals.add("Bat");

           animals.add("Cat");

           animals.add("Dog");

           animals.add("Elephant");

 

           for(String animal : animals){

                System.out.println(animal);

           }

 

     }

 

}


OutPut:

Ant

Bat

Cat

Dog

Elephant


2.2 In Java 8 -> List forEach with  lambda expression or method reference.

Syntax:

void java.lang.Iterable.forEach(Consumer<? super T> action)


Example:  JavaListTest .java


import java.util.ArrayList;

import java.util.List;

 

public class JavaListTest {

     public static void main(String[] args) {

           List<String> animals = new ArrayList<>();

           animals.add("Ant");

           animals.add("Bat");

           animals.add("Cat");

           animals.add("Dog");

           animals.add("Elephant");

          

                    // lambda expression

           System.out.println("List forEach 1==>");        

           animals.forEach(animal -> System.out.println(animal));

          

           System.out.println("List forEach 2==>");        

           animals.forEach(animal -> {

                if ("Dog".equals(animal)) {

                      System.out.println(animal);//// Output : Dog

                }

           });


                    //Stream and filter 

           System.out.println("List forEach 3==>");               

           animals.stream()

                        .filter(f -> f.contains("Ant")).forEach(System.out::println);

     }

}


OutPut:

List forEach 1==>

Ant

Bat

Cat

Dog

Elephant

List forEach 2==>

Dog

List forEach 3==>

Ant


Search
Related Articles

Leave a Comment:
Nyam
at 2020-10-03 21:41:16
Good article