beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Lambda Expression – Iterating Map and List in Java 8

By Chaitanya Singh | Filed Under: Java 8

I have already covered normal way of iterating Map and list in Java. In this tutorial, we will see how to iterate (loop) Map and List in Java 8 using Lambda expression.

Iterating Map in Java 8 using Lambda expression

package com.beginnersbook;
import java.util.HashMap;
import java.util.Map;
public class IterateMapUsingLambda {
	public static void main(String[] args) {
		Map<String, Integer> prices = new HashMap<>();
		prices.put("Apple", 50);
		prices.put("Orange", 20);
		prices.put("Banana", 10);
		prices.put("Grapes", 40);
		prices.put("Papaya", 50);
		
		/* Iterate without using Lambda
		   for (Map.Entry<String, Integer> entry : prices.entrySet()) {
		   System.out.println("Fruit: " + entry.getKey() + ", Price: " + entry.getValue());
		   }
		*/ 
		
		prices.forEach((k,v)->System.out.println("Fruit: " + k + ", Price: " + v));

	}
}

Output:

Fruit: Apple, Price: 50
Fruit: Grapes, Price: 40
Fruit: Papaya, Price: 50
Fruit: Orange, Price: 20
Fruit: Banana, Price: 10

Iterating List in Java 8 using Lambda expression

package com.beginnersbook;
import java.util.List;
import java.util.ArrayList;
public class IterateListUsingLambda {
	public static void main(String[] argv) {
		List names = new ArrayList<>();
		names.add("Ajay");
		names.add("Ben");
		names.add("Cathy");
		names.add("Dinesh");
		names.add("Tom");
		
		/* Iterate without using Lambda
		 Iterator iterator = names.iterator();
		 while (iterator.hasNext()) {
			System.out.println(iterator.next());
		 } 
		*/ 
		names.forEach(name->System.out.println(name));
	}
}

Output:

Ajay
Ben
Cathy
Dinesh
Tom

Comments

  1. SRIKANTH says

    January 27, 2017 at 2:33 PM

    can you explain lamda expressions ?

    Reply
    • Subbiah S says

      October 5, 2019 at 5:37 AM

      Please go through this
      https://beginnersbook.com/2017/10/java-lambda-expressions-tutorial-with-examples/

      Reply

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap