Java 8 forEach Examples

Java 8 has added new way to iterate over List or Collection, by using the new forEach() method of the new Stream class. You can iterate over any Collection like List, Set, or Map by converting them into a java.util.stream.Stream instance and then calling the forEach() method. This method can perform any operation on every element of Stream.

You can also call forEach() method without obtaining Stream from list like listOfString.forEach(), because the forEach() method is also defined in Iterable interface, but obtaining Stream gives you more choices like filtering, mapping or flattening etc.

Please note operation byforEach() method is terminal, that means you cannot reuse the Stream after calling this method.

In this article, I will show you how to use the new Java 8 forEach statements. Below is an example to iterate a List and a Map with the new Java 8 forEach statement.

1. Iterating Map

1.1 Normal way to iterate a map


package com.codehelp.java8;

import java.util.HashMap;
import java.util.Map;

public class Java8ForEachExample {
    public static void main(String[] args) {
        Map<String, Integer> items = new HashMap<>();
        items.put("Alpha", 10);
        items.put("Beta", 20);
        items.put("Charlie", 30);
        items.put("Delta", 40);
        items.put("Echo", 50);
        items.put("Foxtrot", 60);

        for (Map.Entry<String, Integer> entry : items.entrySet()) {
            System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());
        }
    }
}

 

1.2 Java 8 forEach Iteration of Map

package com.codehelp.java8;

import java.util.HashMap;
import java.util.Map;

public class Java8ForEachExample {
    public static void main(String[] args) {
        Map<String, Integer> items = new HashMap<>();
        items.put("Alpha", 10);
        items.put("Beta", 20);
        items.put("Charlie", 30);
        items.put("Delta", 40);
        items.put("Echo", 50);
        items.put("Foxtrot", 60);

        items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
	
        items.forEach((k,v)->{
            System.out.println("Item : " + k + " Count : " + v);
            if("E".equals(k)){
                System.out.println("Hello E");
            }
        });
    }
}

2. Iterating List

2.1 Normal way to iterate a List

package com.codehelp.java8;

import java.util.ArrayList;
import java.util.List;

public class Java8ForEachExample {
    public static void main(String[] args) {

        List items = new ArrayList<>();
        items.add("Alpha");
        items.add("Beta");
        items.add("Charlie");
        items.add("Delta");
        items.add("Echo");
        items.add("Foxtrot");
        
        for(String item : items){
            System.out.println(item);
        }
    }
}

 

2.2 Java 8 forEach Iteration of List


package com.codehelp.java8;

import java.util.ArrayList;
import java.util.List;

public class Java8ForEachExample {
    public static void main(String[] args) {

        List items = new ArrayList<>();
        items.add("Alpha");
        items.add("Beta");
        items.add("Charlie");
        items.add("Delta");
        items.add("Echo");
        items.add("Foxtrot");
        
        //lambda
        //Output : Alpha,Beta,Charlie,Delta,Echo,Foxtrot
        items.forEach(item->System.out.println(item));
            
        //Output : Delta
        items.forEach(item->{
            if("D".equals(item)){
                System.out.println(item);
            }
        });
            
        //method reference
        //Output : Alpha,Beta,Charlie,Delta,Echo,Foxtrot
        items.forEach(System.out::println);
        
        //Stream and filter
        //Output : Foxtrot
        items.stream()
            .filter(s->s.contains("F"))
            .forEach(System.out::println);
        }
}

References:

  1. Java 8 forEach JavaDoc
  2. Java 8 Iterable forEach JavaDoc

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.