Java 8 forEach examples

In this article, we will show you how to loop a List and a Map with the new Java 8 forEach statement.

1. forEach and Map

1.1 Normal way to loop a Map.


	Map<String, Integer> items = new HashMap<>();
	items.put("A", 10);
	items.put("B", 20);
	items.put("C", 30);
	items.put("D", 40);
	items.put("E", 50);
	items.put("F", 60);

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

1.2 In Java 8, you can loop a Map with forEach + lambda expression.


	Map<String, Integer> items = new HashMap<>();
	items.put("A", 10);
	items.put("B", 20);
	items.put("C", 30);
	items.put("D", 40);
	items.put("E", 50);
	items.put("F", 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. forEach and List

2.1 Normal for-loop to loop a List.


	List<String> items = new ArrayList<>();
	items.add("A");
	items.add("B");
	items.add("C");
	items.add("D");
	items.add("E");

	for(String item : items){
		System.out.println(item);
	}

2.2 In Java 8, you can loop a List with forEach + lambda expression or method reference.


	List<String> items = new ArrayList<>();
	items.add("A");
	items.add("B");
	items.add("C");
	items.add("D");
	items.add("E");

	//lambda
	//Output : A,B,C,D,E
	items.forEach(item->System.out.println(item));
		
	//Output : C
	items.forEach(item->{
		if("C".equals(item)){
			System.out.println(item);
		}
	});
		
	//method reference
	//Output : A,B,C,D,E
	items.forEach(System.out::println);
	
	//Stream and filter
	//Output : B
	items.stream()
		.filter(s->s.contains("B"))
		.forEach(System.out::println);

References

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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
java7
Guest
java7

lambda expressions are so unreadable and finally bullshit

jason
Guest
jason

final lamda = bullshit;

Phani
Guest
Phani

Hi:

I keep learning a lot from your examples.. they are simple and to the point..thank you and keep it up.

Pankaj
Guest
Pankaj

//I am looking for loop using streams as follows:

int inputArray[] = {4, 6, 5, -10, 8, 1, 2};

for (int i : inputArray)
{
for (int j = i+1; j {
IntStream.range(i+1,… ).forEach(j -> {// stuck here

});
});

tms
Guest
tms

hello, thanks for this tutorial. In Java 8 possible to use ‘::’ ?
items.forEach(System.out::println);

tms
Guest
tms

I checked it. It is equals the– items.forEach(item->System.out.println(item)); –?
Because the parameter and the return type is the same?
Sorry for dump question .

Aparajith
Guest
Aparajith

Thank you for the simple snippets, to the explanations. Really helpful !!!

Ram
Guest
Ram

Very correct

Abhishek
Guest
Abhishek

can we insert the records in bulk. I don’t want to run the loop again and again. Though of having a batch.
Please suggest.

Josh
Guest
Josh

Clear and simple examples.
Keep it up!

Reader
Guest
Reader

When I do this, I am getting a null pointer exception when the value in the map is null (v is null). How can I avoid that?

items.forEach((k,v)->System.out.println(“Item : ” + k + ” Count : ” + v));

Casey
Guest
Casey

if (items != null) items.forEach((k,v)->System.out.println(“Item : ” + k + ” Count : ” + v));

DucQuoc.wordpress.com
Guest
DucQuoc.wordpress.com

Optional.ofNullable(items).orElse(Collections.emptyMap())
.forEach((k, v) -> System.out.println(“Item : ” + k + ” Count : ” + v));

Ömer Hakan Bilici
Guest
Ömer Hakan Bilici

thanks for clear examples.
In section 2.2, last part – “//Steam and filter” line must be “stream” :) you can remove this comment after fix.

mkyong
Guest
mkyong

Fixed, thanks.

robertmarkbram
Guest
robertmarkbram

Good page. Clear and simple examples. Thanks!

Vijay
Guest
Vijay

Thanks, I was iterating a forEeah loop and instead of sysout. I want to perform few operations but I was getting an error. Your post help me identify what should I do.

Mehdi
Guest
Mehdi

Hi mkyong.??
Can i have your email??

Abdulkadir
Guest
Abdulkadir

You ara wonderfull . You are lord .
Helal olsun krals?n
Thank you
Allah raz? olsun ????

anurag
Guest
anurag

thank you for this nice and post

Edu
Guest
Edu

The only think I don’t like using forEach is when you want to call inside it a service that throws exceptions, because you must catch them inside forEach loop. It doesn’t happen with “for” sentence, as you can have the try outside it.